簡體   English   中英

如何在nodejs中創建雙工stream?

[英]How to create a Duplex stream in nodejs?

我像這樣創建一個新的 Duplex stream

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

通過 Websocket 我收到塊/緩沖區,每次通過 Websocket 進入新塊時,我都會像這樣將其添加到 stream 中:

myStream.push(buffer)

然后我將 pipe stream 轉移到另一個進程(本例中為 ffmpeg)

myStream.pipe(process.stdout); 這會導致錯誤NodeError: The _read() method is not implemented我理解但我不明白為什么以及如何實現它。 我還看到,在 Duplex class 構造函數中,您可以傳遞讀取 function,但為什么這是必要的? 我只想不斷地將塊推入 stream 然后 pipe 到另一個進程

nodejs Duplex stream 要求實現者同時指定寫入和讀取方法:

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場景
上面描述的 websocket 示例可能應該使用 Readable 而不是雙工 stream。 雙工流在存儲轉發或處理轉發場景中很有用。 However, it sounds like the stream in the websocket example is used solely to move data from the websocket to a stream interface. 這可以使用 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 );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM