如何在Node.js中创建双工流?

时间:2019-11-07 11:31:34

标签: javascript node.js stream

我像这样创建一个新的双工流

const Duplex = require('stream').Duplex;
let myStream = new Duplex()

通过Websocket,我收到块/缓冲区,每次通过Websocket传入新块时,我都会像这样将它们添加到流中:

myStream.push(buffer)

然后我将流传输到另一个进程(在此示例中为ffmpeg)

myStream.pipe(process.stdout); 这会导致我理解的错误NodeError: The _read() method is not implemented,但我不明白为什么以及如何实现它。我还看到在Duplex类构造函数中,您可以传递read函数,但是为什么这是必需的呢?我只是想不断将大块推入流中,然后将其通过管道传送到另一个进程

1 个答案:

答案 0 :(得分:0)

nodejs Duplex流要求实现者同时指定write和read方法:

import stream from 'stream';

const duplex = new stream.Duplex({
  write: (chunk, encoding, next) {
    // Do something with the chunk and then call next() to indicate 
    // that the chunk has been processed. The write() fn will handle
    // data piped into this duplex stream. After the write() has
    // finished, the data will be processed by the read() below.
    next();
  },
  read: ( size ) {
    // Add new data to be read by streams piped from this duplex
    this.push( "some data" )
  }
})

有关流的官方nodejs文档可在这里找到:API for Stream Implementers

网络套接字方案
上述的websocket示例可能应该使用Readable而不是双工流。双工流在存储转发或处理转发方案中很有用。但是,听起来好像websocket示例中的流仅用于将数据从websocket移动到流接口。这可以使用Readable来实现:


import stream from 'stream';

const onSocketConnection = ( socket ) => {
    const readable = new stream.Readable({
      // The read logic is omitted since the data is pushed to the socket
      // outside of the script's control. However, the read() function 
      // must be defined.
      read(){}
    });

    socket.on('message', ( data ) => {
        // Push the data on the readable queue
        readable.push( data );
    });

    readable.pipe( ffmpeg );
}