How to close a readable stream (before end)?

Edit: Good news! Starting with Node.js 8.0.0 readable.destroy is officially available: https://nodejs.org/api/stream.html#stream_readable_destroy_error ReadStream.destroy You can call the ReadStream.destroy function at any time. var fs = require(“fs”); var readStream = fs.createReadStream(“lines.txt”); readStream .on(“data”, function (chunk) { console.log(chunk); readStream.destroy(); }) .on(“end”, function () { // This may not been called since we are destroying the stream // … Read more

Using filesystem in node.js with async / await

Native support for async/await fs functions since Node 11 Since Node.JS 11.0.0 (stable), and version 10.0.0 (experimental), you have access to file system methods that are already promisify’d and you can use them with try catch exception handling rather than checking if the callback’s returned value contains an error. The API is very clean and … Read more

How to create full path with node’s fs.mkdirSync?

Update NodeJS version 10.12.0 has added a native support for both mkdir and mkdirSync to create a directory recursively with recursive: true option as the following: fs.mkdirSync(targetDir, { recursive: true }); And if you prefer fs Promises API, you can write fs.promises.mkdir(targetDir, { recursive: true }); Original Answer Create directories recursively if they do not … Read more

Node.js check if file exists

Consider opening the file directly, to avoid race conditions: const fs = require(‘fs’); fs.open(‘foo.txt’, ‘r’, function (err, fd) { // … }); Using fs.existsSync: if (fs.existsSync(‘foo.txt’)) { // … } Using fs.stat: fs.stat(‘foo.txt’, function(err, stat) { if (err == null) { console.log(‘File exists’); } else if (err.code === ‘ENOENT’) { // file does not exist … Read more

Node.js check if path is file or directory

The following should tell you. From the docs: fs.lstatSync(path_string).isDirectory() Objects returned from fs.stat() and fs.lstat() are of this type. stats.isFile() stats.isDirectory() stats.isBlockDevice() stats.isCharacterDevice() stats.isSymbolicLink() // (only valid with fs.lstat()) stats.isFIFO() stats.isSocket() NOTE: The above solution will throw an Error if; for ex, the file or directory doesn’t exist. If you want a true or false … Read more

How to download a file with Node.js (without using third-party libraries)?

You can create an HTTP GET request and pipe its response into a writable file stream: const http = require(‘http’); // or ‘https’ for https:// URLs const fs = require(‘fs’); const file = fs.createWriteStream(“file.jpg”); const request = http.get(“http://i3.ytimg.com/vi/J—aiyznGQ/mqdefault.jpg”, function(response) { response.pipe(file); // after download completed close filestream file.on(“finish”, () => { file.close(); console.log(“Download Completed”); }); … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)