Required Package
http
or
https
and
fs
Installation of Required Package
using npm
npm install <package>
Code
To download a file from an url <url> to the given path <path> and name it as filename <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
Reference