簡體   English   中英

`Duplex.from()` 拋出`“可迭代”參數必須是可迭代的實例。 接收到 Object 的實例

[英]`Duplex.from()` throws `The "iterable" argument must be an instance of Iterable. Received an instance of Object`

我很困惑。 Duplex.from()方法可以將 object 作為src並從 object 屬性創建一個writable readable雙工 stream:

readablewritable轉換為 Stream,然后將它們組合成 Duplex,其中 Duplex 將寫入可寫並從可讀讀取。

為什么我的示例不起作用?

const { PassThrough, Duplex } = require("stream");


const loopback = new PassThrough();


const duplex = Duplex.from({
    writable: loopback,
    readable: loopback
});


duplex.on("data", (chunk) => {
    console.log("Data on duplex", chunk)
});


duplex.write("Hello World");

我的預期結果是創建了雙工 stream,如果是這樣,輸出與輸入相同。 (與“回聲”或普通直通流相同)

錯誤信息:

[nodemon] starting `node index.js`
internal/streams/from.js:32
    throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The "iterable" argument must be an instance of Iterable. Received an instance of Object
    at new NodeError (internal/errors.js:322:7)
    at from (internal/streams/from.js:32:11)
    at Function.Readable.from (internal/streams/readable.js:1368:10)
    at Object.<anonymous> (/home/marc/projects/test-stream/index.js:7:23)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)
    at internal/main/run_main_module.js:17:47 {
  code: 'ERR_INVALID_ARG_TYPE'
}

有人可以向我解釋為什么我不能從 object 創建雙工 stream 嗎?

我有點迷茫,因為文檔說您可以將 object 作為參數傳遞,但錯誤消息說“必須是 Iterable 的實例”。 據我所知, object 是可迭代的。 那么這里的問題是什么?

沒關系,我發現了我的錯誤。

我使用的是過時的節點版本:

node -v
v14.19.0

我通過 nodesource ( https://github.com/nodesource/distributions#deb ) 更新到 node.js v16:

curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt-get install -y nodejs

它按預期工作。

暫無
暫無

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

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