Categories
JavaScript Answers

How to send file in response with Node.js?

Spread the love

To send file in response with Node.js, we call pipe to pipe a stream.

For instance, we write

const http = require("http");
const fileSystem = require("fs");
const path = require("path");

http
  .createServer((request, response) => {
    const filePath = path.join(__dirname, "myfile.mp3");
    const stat = fileSystem.statSync(filePath);

    response.writeHead(200, {
      "Content-Type": "audio/mpeg",
      "Content-Length": stat.size,
    });

    const readStream = fileSystem.createReadStream(filePath);
    readStream.pipe(response);
  })
  .listen(2000);

to call createServer with a callback that calls createReadStream to read the file at filePath.

Then we call readStream.pipe with response to pipe the file data as the response.

We call writeHead to write the file metadata as the header.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *