download file node js code example
Example 1: download file nodejs
const http = require('http');
const fs = require('fs');
const url = 'www.example.com/image.png';
const path = 'app/assets/my_image_name.xlsx'
const request = http.get(url, function(response) {
if (response.statusCode === 200) {
var file = fs.createWriteStream(path);
response.pipe(file);
}
request.setTimeout(60000, function() {
request.abort();
});
});
Example 2: node js download file to folder
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);
});
}).on('error', function(err) {
fs.unlink(dest);
if (cb) cb(err.message);
});
};
Example 3: download a file nodejs
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);
});