Node + Express: Download files with

Last updated on March 19, 2022 Hadrianus Loading... Post a comment

The example below shows you how to automatically download an image served from Express server when clicking a link.

1. Navigate to the folder you want your project to lie in then run:

npm init

2. Install express:

npm i express

3. Create a new folder named files. Copy into this folder an image named test.jpg. You can use an image from your computer or download the sample from here:

Our project structure:

├── files
│   └── test.jpg
├── index.js
├── node_modules
├── package-lock.json
└── package.json

4. Add the following code to index.js:

const path = require("path");
const express = require("express");

const app = express();
const port = 3000;

app.use(express.static(path.join(__dirname, "files")));

const fileName = 'test.jpg';
const fileUrl = `http://localhost:${port}/${fileName}`;
const filePath = path.join(__dirname, 'files', fileName);

app.get("/", (req, res, next) => {
  <img src=${fileUrl} />
  <a href="/download">Download</a>

app.get("/download", (req, res, next) => {;


5. Get our project up and running by executing the following command:

node app.js

Open http://localhost:3000 with your browser and hit “Download” to see what happens:

That’s it. Further reading:

You can also check out our Node.js category page for the latest tutorials and examples.

Notify of
Inline Feedbacks
View all comments

Related Articles