How To Download Files With NodeJS – Simple Examples

Welcome to a tutorial on how to download files with NodeJS. Need to download a document or image in NodeJS? No problem – We can do it very easily in modern NodeJS.

To download a file in NodeJS (from a remote server), simply fire an HTTP request and pipe the results to a file stream.

  • const https = require("https"), fs = require("fs");
  • const source = "https://site.com/img.jpg", target = "./img.jpg";
  • https.get(source, res => { res.pipe(fs.createWriteStream(target)); });

That covers the quick basics, but read on for better examples!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes Node Download Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

NODEJS DOWNLOAD FILE

All right, let us now get into the examples of how to download files in NodeJS.

 

1) DOWNLOAD WITH NATIVE HTTP & FS

1-http.js
// (A) LOAD MODULES
const https = require("https"),
      fs = require("fs");

// (B) SOURCE & TARGET
var source = "https://upload.wikimedia.org/wikipedia/en/d/d0/Dogecoin_Logo.png",
    target = "./doge.png";

// (C) HTTP GET
https.get(source, res => {
  // (C1) CANNOT ACCESS SPECIFIED FILE ON REMOTE SERVER
  if (res.statusCode != 200) {
    console.log(res.statusCode);
    console.log(res.statusMessage);
  }

  // (C2) PROCEED
  else {
    // (C2A) PIPE TO FILE STREAM
    let stream = fs.createWriteStream(target);
    res.pipe(stream);

    // (C2B) ON FINISH
    stream.on("finish", () => {
      stream.close();
      console.log("Download OK");
    });

    // (C2C) OPTIONAL - HANDLE FILE STREAM ERROR
    stream.on("error", err => {
      console.log(err);
    });
  }
})

// (C3) OPTIONAL - ON GET ERROR
.on("error", err => {
  console.log(err);
});

No need to panic. This is actually the same as the introduction snippet above, just expanded to handle errors better:

  • Take note that servers can return a response, but the file is not found (404), has no access permission (403), or could be anything else. This is where we use if (res.statusCode != 200) to capture all the server-side errors.
  • stream.on("error") should be self-explanatory, handle the error if Node fails to write the file.
  • https.on("error") as well, if there is no response from the server or the Internet connection is down.

 

 

2) DOWNLOAD WITH AXIOS

2-axios.js
// (A) LOAD MODULES
const axios = require("axios"),
      fs = require("fs");

// (B) SOURCE & TARGET
var source = "https://upload.wikimedia.org/wikipedia/en/d/d0/Dogecoin_Logo.png",
    target = "./doge.png";

// (C) GET REQUEST
// (C1) INIT REQUEST
axios({
  method: "get",
  url: source,
  responseType: "stream"
})

// (C2) OK - PROCEED SAVE
.then(res => {
  // (C2A) PIPE TO FILE STREAM
  let stream = fs.createWriteStream(target);
  res.data.pipe(stream);

  // (C2B) ON FINISH
  stream.on("finish", () => {
    stream.close();
    console.log("Download OK");
  });

  // (C2C) OPTIONAL - HANDLE FILE STREAM ERROR
  stream.on("error", err => {
    console.log(err);
  });
})

// (C3) OPTIONAL - CATCH HTTP ERROR
.catch(err => {
  console.log("xxx");
  console.log(err);
});

For you guys who are using Axios, Got, or Fetch to do HTTP requests – It is pretty much the same process. Just fire the HTTP request, and pipe the data into a file stream.

 

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

INFOGRAPHIC CHEAT SHEET

Download Files With NodeJS (Click To Enlarge)

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *