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

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

    All the answers listed appear to open the Readable Stream in flowing mode which is not the default in NodeJS and can have limitations since it lacks backpressure support that NodeJS provides in Paused Readable Stream Mode. Here is an implementation using Just Buffers, Native Stream and Native Stream Transforms and support for Object Mode

    import {Transform} from 'stream';
    
    let buffer =null;    
    
    function objectifyStream() {
        return new Transform({
            objectMode: true,
            transform: function(chunk, encoding, next) {
    
                if (!buffer) {
                    buffer = Buffer.from([...chunk]);
                } else {
                    buffer = Buffer.from([...buffer, ...chunk]);
                }
                next(null, buffer);
            }
        });
    }
    
    process.stdin.pipe(objectifyStream()).process.stdout
    

提交回复
热议问题