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


Question

How do I download a file with Node.js without using third-party libraries?

I don't need anything special. I only want to download a file from a given URL, and then save it to a given directory.

1
370
9/18/2018 9:21:40 AM

Accepted Answer

You can create an HTTP GET request and pipe its response into a writable file stream:

const http = require('http');
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);
});

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.

501
1/18/2019 5:16:11 PM

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);
  });
};

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon