1.

How to download a file in Express.js?

Answer»

To DOWNLOAD a FILE through Node.js requires a lot of effort and the code can get complicated SOON. But the process is very EASY with express.

We will see the same through a small example app. First create a new Node.js APPLICATION by creating a directory and changing to it. Then will initialize a package.json file with the npm init -y command. It will give all options as yes and if we don’t give it, we will have to manually type yes.

Next, we will install express in the app by giving the npm i express command.  

Next, add an image file in the root directory. We’ll add desktop.jpg in the root directory.

Now, create a new file index.js. First, we will import the required express import. Then we have an app.get() function for the home directory. Now inside the get function, in the response object we are using the download function and passing our image desktop.jpg. 

Lastly, we are listening at port 3000 for incoming requests. 

After that start the node server by giving node index.js in the terminal.

Now, when we go to localhost:3000 the image file desktop.jpg will be downloaded automatically.



Discussion

No Comment Found