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

后端 未结 18 2249
日久生厌
日久生厌 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条回答
  •  北海茫月
    2020-11-29 19:15

    Hope this is more useful than the above answer:

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

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

    Also, this code may produce unpredictable failures for non-ASCII text (it assumes that every character fits in a byte), but perhaps you do not care about that, either.

提交回复
热议问题