Welcome folks today in this blog post we will be downloading images from url using node-fetch
library in express.js. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the node-fetch
library using the npm
command a shown below
npm i node-fetch
npm i express
After this you need to make an index.js
file and copy paste the following code
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
const fs = require("fs"); // Built-in filesystem package for Node.js const fetch = require("node-fetch"); const express = require("express"); const bodyparser = require('body-parser') const app = express(); app.use(bodyparser.urlencoded({extended:false})) app.use(bodyparser.json()) app.get("/", (req, res) => { res.sendFile(__dirname + "/index.html"); }); app.post("/downloadimage", (req, res) => { const imageUrl = req.body.url let outputPath = Date.now() + "output.png" fetch(imageUrl).then((res) => res.body.pipe(fs.createWriteStream(outputPath)) ); res.download(outputPath,(req,res) => { }) }); const port = 5000; app.listen(port, () => { console.log("App is listening on port 5000"); }); |
As you can see we are loading the node-fetch
and express library. And also we are including the body parser middleware since we are working with html forms. And now we are loading the index.html
file when the user go to the index page and then we are also writing the post request when the users submits the form inside this we are making a request to the url that we receive using the node-fetch
module and after that inside the promise we are saving the file first of all inside the local drive and then downloading it as an attachment using the download()
method of express
Now you need to create the index.html
file which will contain the simple form
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Download Image From URL in Node-fetch</title> </head> <body> <form action="/downloadimage" method="post"> <input type="text" name="url" placeholder="Enter URL of Image" required id=""> <input type="submit" value="Download Image"> </form> </body> </html> |