【问题标题】:Transform JS objects to JSON using transform stream使用转换流将 JS 对象转换为 JSON
【发布时间】:2018-08-25 23:30:09
【问题描述】:

请注意,有许多转换流可以做到这一点:

JSON -> JS

但我希望创建一个可以执行以下操作的 Node.js 转换流:

JS -> JSON

我有一个可读流:

const readable = getReadableStream({objectMode:true});

可读流输出对象,而不是字符串。

我需要创建一个转换流,它可以过滤其中一些对象并将对象转换为 JSON,如下所示:

const t = new Transform({
  objectMode: true,
  transform(chunk, encoding, cb) {
    if(chunk && chunk.marker === true){
       this.push(JSON.stringify(chunk));
     }
    cb();
  },
  flush(cb) {
    cb();
  }
});

但是,由于某种原因,我的转换流不能接受转换方法的对象,只有字符串和缓冲区,我该怎么办?

我尝试添加这两个选项:

  const t = new Transform({
      objectMode: true,
      readableObjectMode: true,  // added this
      writableObjectMode: true,  // added this too
      transform(chunk, encoding, cb) {
        this.push(chunk);
        cb();
      },
      flush(cb) {
        cb();
      }
    });

不幸的是,我的转换流仍然不能接受对象,只能接受字符串/缓冲区。

【问题讨论】:

    标签: node.js node-streams nodejs-stream


    【解决方案1】:

    您只需在转换流上使用writableObjectMode: true

    Documentation

    options <Object> Passed to both Writable and Readable constructors. Also has the following fields:
        readableObjectMode <boolean> Defaults to false. Sets objectMode for readable side of the stream. Has no effect if objectMode is true.
        writableObjectMode <boolean> Defaults to false. Sets objectMode for writable side of the stream. Has no effect if objectMode is true.
    

    您希望转换流的可写部分接受对象,因为对象已写入其中。虽然将从中读取字符串。

    查看这个最小的工作示例:

    const { Readable, Writable, Transform } = require('stream');
    
    let counter = 0;
    
    const input = new Readable({
      objectMode: true,
      read(size) {
        setInterval( () => {
          this.push({c: counter++});  
        }, 1000);  
      }  
    });
    
    const output = new Writable({
      write(chunk, encoding, callback) {
        console.log('writing chunk: ', chunk.toString());
        callback();  
      }  
    });
    
    const transform = new Transform({
      writableObjectMode: true,
      transform(chunk, encoding, callback) {
        this.push(JSON.stringify(chunk));
        callback();  
      }  
    });
    
    input.pipe(transform);
    transform.pipe(output);
    

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 1970-01-01
      • 2020-11-02
      • 2011-03-13
      • 1970-01-01
      • 1970-01-01
      • 2017-06-16
      • 2016-02-02
      相关资源
      最近更新 更多