0

I want to send data using the stream in nodejs. I tried to send the data using pipe but it didn't work, please help me out.

const { Readable } = require("stream")

app.get('/test', async (req, res) => {
  let month = ['jan','feb','mar','apr','may','jun','jul'];
  let stream = new Readable({read(size){}});
  stream.setEncoding('utf8')
      
  for (let m of month) {
    stream.push(m)
  }
       
  stream.on('data', (data) => {
    console.log(data)
    res.write(data,'utf8')
  })
   
  stream.on('end',() => {
    res.end();
  })
})

I also tried this but did not work...

const { Readable } = require("stream")

app.get('/test', async (req,res) => {
  let month = ['jan','feb','mar','apr','may','jun','jul'];
  let stream = new Readable({read(size){}});
  stream.setEncoding('utf8')
      
  for (let m of month) {
    stream.push(m)
  }
      
  stream.pipe(res)  
})
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
abhimanyu
  • 165
  • 3
  • 12
  • what errors (if any) are you getting? – LostJon Sep 10 '21 at 12:04
  • Does this answer your question? [How to emit/pipe array values as a readable stream in node.js?](https://stackoverflow.com/questions/16848972/how-to-emit-pipe-array-values-as-a-readable-stream-in-node-js) – eol Sep 10 '21 at 12:10
  • EOL- i want to send data in res in chunk using pipe. I tried solution followed by your link but it didn't work – abhimanyu Sep 15 '21 at 10:57

1 Answers1

1

You must also end the stream with a stream.push(null) after the for loop. See https://nodejs.org/dist/latest-v14.x/docs/api/stream.html#stream_readable_push_chunk_encoding:

Passing chunk as null signals the end of the stream (EOF), after which no more data can be written.

Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31