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

后端 未结 18 2329
日久生厌
日久生厌 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:13

    Streams don't have a simple .toString() function (which I understand) nor something like a .toStringAsync(cb) function (which I don't understand).

    So I created my own helper function:

    var streamToString = function(stream, callback) {
      var str = '';
      stream.on('data', function(chunk) {
        str += chunk;
      });
      stream.on('end', function() {
        callback(str);
      });
    }
    
    // how to use:
    streamToString(myStream, function(myStr) {
      console.log(myStr);
    });
    

提交回复
热议问题