javascriptnode.jsdownloadfs

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


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.


Solution

  • As of Node 18, you can use the built-in fetch global, which implements the Fetch API to download data with several methods built in to directly work with the result as plain text, JS-converted-from-JSON, or binary data (as ArrayBuffer).

    For older versions of Node, 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");
       });
    });
    

    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.

    More detailed explanation in https://sebhastian.com/nodejs-download-file/