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:// URLsconst 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);});
If you want to support gathering information on the command line--like specifying a target file or directory, or URL--check out something like Commander.
Don't forget to handle errors! The following code is based on Augusto Roman's answer.
var http = require('http');var fs = require('fs');var download = function(url, dest, cb) { var file = fs.createWriteStream(dest); var request = http.get(url, function(response) { response.pipe(file); file.on('finish', function() { file.close(cb); // close() is async, call cb after close completes. }); }).on('error', function(err) { // Handle errors fs.unlink(dest); // Delete the file async. (But we don't check the result) if (cb) cb(err.message); });};
As Michelle Tilley said, but with the appropriate control flow:
var http = require('http');var fs = require('fs');var download = function(url, dest, cb) { var file = fs.createWriteStream(dest); http.get(url, function(response) { response.pipe(file); file.on('finish', function() { file.close(cb); }); });}
Without waiting for the finish
event, naive scripts may end up with an incomplete file.
Edit: Thanks to @Augusto Roman for pointing out that cb
should be passed to file.close
, not called explicitly.