Inside this article we will see the concept of download image from url in node js. Downloading image from urls are very common method in any application. We will see all easy steps to download an image here.
Tutorial is very interesting and also easy to implement in your code. If you are looking an article which makes you understand how to download an image from url in node js then this article is good place to go.
Node JS is an environment where we can deploy and execute javascript based applications. In this article we will see how to download an image from url in node js.
Learn More –
- How to Send Email Using Gmail SMTP in Node Js
- Node Express Sequelize ORM CRUD APIs with MySQL
- Node Js Send Email with Attachment Using Gmail SMTP
- Convert Image File to Base64 String in Node Js Tutorial
Let’s get started.
Node Js Application Setup
Please make sure you have node and npm both installed. To check available versions use these commands.
To check node version
$ node -v
To check npm version
$ npm -v
Create a folder with any name say downloadimage. Open this folder into terminal or command prompt.
Next, we need package.json file. Run this given command into terminal
$ npm init -y
The given command will auto generate package.json file with default values.
Next we need to create a file say server.js into node application.
Download Image Code
Open server.js file and write this following code into it.
var fs = require('fs'), http = require('http'), https = require('https'); var Stream = require('stream').Transform; // Download Image Helper Function 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(); }; // Calling Function to Download downloadImageFromURL('https://onlinewebtutorblog.com/wp-content/uploads/2021/05/cropped-cropped-online-web-tutor-logo.png', 'onlinewebtutor.png');
Application Testing
Open project into terminal and type this command.
$ node server.js
When you hit this, it will download an image from the given url and place it to your node application.
We hope this article helped you to learn How To Download an Image From URL in Node Js Tutorial in a very detailed way.
[do_widget “buy me a coffee”]
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.