How does . pipe() work on Node.js?

Asked

Viewed 102 times

6

I have a question about how the .pipe(). I saw videos and read the documentation, but I’m not sure how it works.

From what I understand, he basically takes the information from a readableStream and pass it on to a writeableStream, but I’m not sure I know how to use it the right way. To clarify what I’m saying I’ll put a code of mine that went wrong:

const fs = require('fs')
const http = require('http')

const port = 8000
const file = './file.txt'

const readStream = fs.createReadStream(file)


const server = http.createServer((req, res) => {
  res.on('pipe', fileContent => console.log(fileContent.toString()))
  readStream.pipe(res)
})

server.listen(port, () => console.log('Server is Runing...'))

My goal in this part was to create an http server and pass the contents inside the file through the console as a response (Obs: in the file only has any text of a line). My server runs, but nothing appears on the console. I wanted to understand what might be going wrong because I do not know how to receive the contents of the file I sent.

1 answer

7


Basically, the method of pipe "directs" the flow of a readable stream for a writable stream. In the case of the question, pipe the "packages" of the read stream from the archive to the write stream of the HTTP server.


In fact, the stream works properly on first requisition.

Note that you are creating the read stream out of of Handler server, so that, in the first request, the stream will be fully consumed. So, from the second request, there will be no more to read, since all data will have been exhausted.

It is ideal, therefore, that you create a read stream for each requisition. Something like that:

const server = http.createServer((req, res) => {
  res.on('pipe', () => console.log('Pipe chamado.'));

  const readStream = fs.createReadStream(file);
  readStream.pipe(res);
});

Note now that a new read stream will be created for each request. Note also that I modified the console.log since the method toString does not, in this case, what you think.

The event pipe is called with a type parameter stream.Readable. So if you want to print the read data on the console, you can do something like:

const server = http.createServer((req, res) => {
  res.on('pipe', (src) => {
    src.on('data', (chunk) => {
      console.log(chunk.toString('utf8'));
    });
  });

  const readStream = fs.createReadStream(file);
  readStream.pipe(res);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.