Download a file with given url with Node.js -- ESModule | Node.js | JS

Required Package 

http 
or 
https

and 

fs

Installation of Required Package

using npm

npm install 

Code

To download a file from an url  to the given path and name it as filename ,

write these in a .js file and execute it with node.js .

const http = require('http'); // or 'https' for https:// URLs
const fs = require('fs');

var filename = ""; // with file extension
var url = ""; // with file extension

const file = fs.createWriteStream(filename);

const request = http.get(url, function(response) {
   response.pipe(file);

   // after download completed close filestream
   file.on("finish", () => {
       file.close();
       console.log("Download Completed");
   });
});

Example

Example 1 

Code

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

Output

Write code from above example into test3.js. Save it as test3.js. After executing test3.js with node.js. The result should be

Download a file with given url with Node.js -- ESModule | Node.js | JS_第1张图片

Reference

Download a file with given url with Node.js -- ESModule | Node.js | JS_第2张图片

 

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

 

 

你可能感兴趣的:(node.js,javascript,开发语言)