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

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

    And yet another one for strings using promises:

    function getStream(stream) {
      return new Promise(resolve => {
        const chunks = [];
    
        # Buffer.from is required if chunk is a String, see comments
        stream.on("data", chunk => chunks.push(Buffer.from(chunk)));
        stream.on("end", () => resolve(Buffer.concat(chunks).toString()));
      });
    }
    
    

    Usage:

    const stream = fs.createReadStream(__filename);
    getStream(stream).then(r=>console.log(r));
    

    remove the .toString() to use with binary Data if required.

    update: @AndreiLED correctly pointed out this has problems with strings. I couldn't get a stream returning strings with the version of node I have, but the api notes this is possible.

提交回复
热议问题