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

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

    This worked for me and is based on Node v6.7.0 docs:

    let output = '';
    stream.on('readable', function() {
        let read = stream.read();
        if (read !== null) {
            // New stream data is available
            output += read.toString();
        } else {
            // Stream is now finished when read is null.
            // You can callback here e.g.:
            callback(null, output);
        }
    });
    
    stream.on('error', function(err) {
      callback(err, null);
    })
    

提交回复
热议问题