obrienmd obrienmd - 1 year ago 133
Node.js Question

Writing node.js stream into a string variable

I'm hacking on a node.js program that captures SMTP mails and acts on the mail data. The 'smtp-protocol' node library provides the mail data live as a stream, and as a node.js newbie I'm not sure how to write that stream into a string variable. I currently have it writing to stdout using the line:

stream.pipe(process.stdout, { end : false });

As I said, I need to get this stream data writing to a string variable instead, which I will then use once the stream has ended.

Help much appreciated!

Answer Source

The key is to use these two Stream events:

  • Event: 'data'
  • Event: 'end'

For stream.on('data', ...) you should collect your data data into either a Buffer (if it is binary) or into a string.

For on('end', ...) you should call a callback with you completed buffer, or if you can inline it and use return using a Promises library.