Categories
JavaScript Answers

How to stream files in Node Express to client?

Spread the love

To stream files in Node Express to client, we create a read stream and pipe it.

For instance, we write

app.use((req, res, next) => {
  if (req.url === "somethingorAnother") {
    res.setHeader("content-type", "some/type");
    fs.createReadStream("./toSomeFile").pipe(res);
  } else {
    next();
  }
});

to call createReadStream to create a read stream to read toSomeFile.

And we call pipe with res to pipe the read stream as the response.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.