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

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

    Using the quite popular stream-buffers package which you probably already have in your project dependencies, this is pretty straightforward:

    // imports
    const { WritableStreamBuffer } = require('stream-buffers');
    const { promisify } = require('util');
    const { createReadStream } = require('fs');
    const pipeline = promisify(require('stream').pipeline);
    
    // sample stream
    let stream = createReadStream('/etc/hosts');
    
    // pipeline the stream into a buffer, and print the contents when done
    let buf = new WritableStreamBuffer();
    pipeline(stream, buf).then(() => console.log(buf.getContents().toString()));
    

提交回复
热议问题