How to Download Image from URL in Node JS?

Today, i will let you know example of node js download image from url. We will look at example of how to download image from url in node js. if you want to see example of node js get image from url then you are a right place. i explained simply about node js download file from url.

I will give you very simple example of how to download image or file from url in node.js app. let’s see bellow example code:

Step 1: Create Node App

run bellow command and create node app.

mkdir my-app

cd my-app

npm init

Step 2: Create server.js file

server.js

var fs = require('fs'),

http = require('http'),

https = require('https');

var Stream = require('stream').Transform;

var downloadImageFromURL = (url, filename, callback) => {

var client = http;

if (url.toString().indexOf("https") === 0){

client = https;

}

client.request(url, function(response) {

var data = new Stream();

response.on('data', function(chunk) {

data.push(chunk);

});

response.on('end', function() {

fs.writeFileSync(filename, data.read());

});

}).end();

};

downloadImageFromURL('https://www.itsolutionstuff.com/assets/images/logo-it.png', 'it.png');

now you can simply run by following command:

node server.js

i hope it can help you…

Leave a Comment