How to send the file from Nodejs to the client?

Tameem Rafay
2 min readNov 24, 2022

--

In this article, we will review how to send the file from your Node.js server to your client. Sending the file will be very destructive to your server performance if you don't handle this with proper care.

Let’s say your server RAM is 1GB and you want to send a file of 4GB to your client what will happen in the worst case? Yes, your server might crash because it will load the whole file in your RAM before sending it to your client.

How to send files in streams

Now there is another approach to sending the file from the server in the stream. In the stream, we will send the file in chunks of small sizes. It will load the file from breaks in small packets and load it to RAM and transfer it to the client.

In this example, we are using the Node.js language on the server side, and on the client side, we will download the file in React.js

Server Side: How to send files in Node.js in streams?

const fs = require("fs");
const util = require("util");
const unlinkFile = util.promisify(fs.unlink); // to del file from local storage
const path = `upload/invoice.pdf`; // path where to file is stored in server
const rs = fs.createReadStream(path);

// -------------------------------------------------------
// --- res variable is to send the response back to client
//--------------------------------------------------------

async getFile(req, res){

// get size of the video file
const { size } = fs.statSync(path);
res.setHeader("Content-Type", "application/pdf");
res.setHeader("Content-Length", size);
rs.pipe(res);

// delete the file on server after it sends to client
rs.on('end', () => {
await unlinkFile(filePath);
});

}

If you hit the API on postman you can check the file is downloaded.

Receive the file in streams in postman

Now it's time to receive the image in react.js code. Sometimes you will not get the response so you need to force to receive the data in the blob.

let header = {
"Content-Type": "application/json",
};

const response = await axios(
`${API_URL}`,
{
method: "GET",
responseType: "blob", //Force to receive data in a Blob Format
},
{ headers: header }
);

return response.data;

const file = new Blob([response.data], { type: "application/pdf" });
const fileURL = URL.createObjectURL(file);
window.open(fileURL); // open the pdf file to the new window to view/download

--

--