how to download file from url in 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: nodejs download image from url
var fs = require('fs'),
request = require('request');
var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
console.log('done');
});
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);
});