Read contents of Node.js stream into a string variable


Question

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!

1
71
3/22/2019 1:37:57 AM

Accepted Answer

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.

28
5/16/2012 5:54:03 PM

Hope this is more useful than the above answer (which now has a broken link).

Also note that string concatenation is not an efficient way to collect the string parts, but it is used for simplicity (and perhaps your code does not care about efficiency)

var string = '';
stream.on('data',function(data){
  string += data.toString();
  console.log('stream data ' + part);
});


stream.on('end',function(){
 console.log('final output ' + string);
});

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon