I am creating a website for my school and I want to allow the students to be able to download files (pdfs) using node js. So basically, they would see a bunch of different links and when they click any link the downloading would start.
Asked
Active
Viewed 675 times
0
-
Related: https://stackoverflow.com/questions/11944932/how-to-download-a-file-with-node-js-without-using-third-party-libraries – pkyo Sep 28 '20 at 20:38
-
So the download should be done via a backend NodeJS service and not directly from the web page using an URL pointing to the file location? – Christian Sep 28 '20 at 20:58
1 Answers
0
You tagged this express
so I'm going to assume you already have express installed via npm. I'm also going to assume the files you want are in the downloads
directory in that folder. Express actually has a res.download
module, too, so I used that in this simple example:
const express = require("express");
const path = require("path");
const app = express();
app.get("/downloads/:file", (req, res) => {
res.download(
path.join(__dirname, "downloads/" + req.params.file),
(err) => {
if (err) res.status(404).send("<h1>Not found: 404</h1>");
}
);
});
app.get("/", (req, res) => {
res.send(`
<ul>
<li>
<a href="/downloads/file1.pdf">
file1.pdf
</a>
</li>
<li>
<a href="/downloads/file2.pdf">
file2.pdf
</a>
</li>
<li>
<a href="/downloads/file3.pdf">
file3.pdf
</a>
</li>
</ul>`);
});
app.listen(3000);
So when a user goes to http://localhost:3000/downloads/file.pdf
, Express will send the file to download in ./downloads/file.pdf

Nathan Chu
- 635
- 1
- 3
- 19