Member-only story

Download files in Javascript from Node.js server

Bogdan Alexandru Militaru
2 min readJul 17, 2020

Download files in Javascript from the Node.js server using the Express.js framework. Hi there, long time no see. In this article, I want to show you how to download files in Javascript, either you use Vue.js, React, Angular, jQuery, or Vanilla JS. On the backend side, we run on Node.js using Express.js, and I write only the route’s handler.

Back-end

import cors from 'cors';
import fs from 'fs';
.get('/download',
cors({
exposedHeaders: ['Content-Disposition'],
}),
async (req, res) => {
try {
const fileName = 'file.pdf'
const fileURL = '/path/to/file/file.pdf'
const stream = fs.createReadStream(fileURL);
res.set({
'Content-Disposition': `attachment; filename='${fileName}'`,
'Content-Type': 'application/pdf',
});
stream.pipe(res);
} catch (e) {
console.error(e)
res.status(500).end();
}
};
})

This code is all you need to download any file from the back-end. In this example, I used a .pdf file, but you can change the content type, on line 15.

Is very important to use CORS as middleware to determine what headers are exposedtoAxios library, on the front-end side. We need to set Content-Disposition, declared on line _1_4, to inform the client about this request which has an…

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

Write a response