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

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

    What about something like a stream reducer ?

    Here is an example using ES6 classes how to use one.

    var stream = require('stream')
    
    class StreamReducer extends stream.Writable {
      constructor(chunkReducer, initialvalue, cb) {
        super();
        this.reducer = chunkReducer;
        this.accumulator = initialvalue;
        this.cb = cb;
      }
      _write(chunk, enc, next) {
        this.accumulator = this.reducer(this.accumulator, chunk);
        next();
      }
      end() {
        this.cb(null, this.accumulator)
      }
    }
    
    // just a test stream
    class EmitterStream extends stream.Readable {
      constructor(chunks) {
        super();
        this.chunks = chunks;
      }
      _read() {
        this.chunks.forEach(function (chunk) { 
            this.push(chunk);
        }.bind(this));
        this.push(null);
      }
    }
    
    // just transform the strings into buffer as we would get from fs stream or http request stream
    (new EmitterStream(
      ["hello ", "world !"]
      .map(function(str) {
         return Buffer.from(str, 'utf8');
      })
    )).pipe(new StreamReducer(
      function (acc, v) {
        acc.push(v);
        return acc;
      },
      [],
      function(err, chunks) {
        console.log(Buffer.concat(chunks).toString('utf8'));
      })
    );
    

提交回复
热议问题