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

How to append to a file in Node?

For occasional appends, you can use appendFile, which creates a new file handle each time it’s called: Asynchronously: const fs = require(‘fs’); fs.appendFile(‘message.txt’, ‘data to append’, function (err) { if (err) throw err; console.log(‘Saved!’); }); Synchronously: const fs = require(‘fs’); fs.appendFileSync(‘message.txt’, ‘data to append’); But if you append repeatedly to the same file, it’s much … 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

Writing to files in Node.js

There are a lot of details in the File System API. The most common way is: const fs = require(‘fs’); fs.writeFile(“/tmp/test”, “Hey there!”, function(err) { if(err) { return console.log(err); } console.log(“The file was saved!”); }); // Or fs.writeFileSync(‘/tmp/test-sync’, ‘Hey there!’);