Download remote server files using Node.js

    Nov 30, 2016       by Pankaj Kumar

In this demo, we will learn how to download files from remote server to our local system.

We can download files from remote server from multiple ways, I am going to discuss you the most easiest way by using only two packages of nodejs which are fs & request.

So look at the folder stucture first:

 
icons/
node_modules/
package-lock.json
server.js
 

 

In the icon folder images will be stored, node_modules is for nodejs installed package, package-lock.json file which creates automatically when node packages gets intalled and at last server.js which is having the actual code for the required task.

 

So let's have a look on the code below under server.js:

 
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.cryptocompare.com/media/19684/doge.png', 'icons/taskks12.png', function(){
    console.log('done');
});
 


In the above code we can see, there are two package included in the file, And at the mid we have created a method which takes 3 parameters first the remote url of the file. second the file name with path where image and the last parameter for callback function.

I hope it worked for you.

Find complete source code over GitHub


WHAT'S NEW

Find other similar Articles here: