How do I read the contents of a Node.js stream into a string variable?

后端 未结 18 2317
日久生厌
日久生厌 2020-11-29 18:55

I\'m hacking on a Node program that uses smtp-protocol to capture SMTP emails and act on the mail data. The library provides the mail data as a stream, and I don\'t know how

18条回答
  •  旧时难觅i
    2020-11-29 19:09

    (This answer is from years ago, when it was the best answer. There is now a better answer below this. I haven't kept up with node.js, and I cannot delete this answer because it is marked "correct on this question". If you are thinking of down clicking, what do you want me to do?)

    The key is to use the data and end events of a Readable Stream. Listen to these events:

    stream.on('data', (chunk) => { ... });
    stream.on('end', () => { ... });
    

    When you receive the data event, add the new chunk of data to a Buffer created to collect the data.

    When you receive the end event, convert the completed Buffer into a string, if necessary. Then do what you need to do with it.

提交回复
热议问题