node.js - NodeJS 流不等待异步

标签 node.js typescript ecmascript-6 es6-promise nodejs-stream

我在测试 NodeJS 流时遇到了问题。我似乎无法让我的项目在运行 Stream.pipeline 后等待 Duplex 和 Transform 流的输出,即使它返回了一个 promise 。也许我遗漏了一些东西,但我相信脚本应该等待函数返回然后再继续。我正在尝试开展的项目中最重要的部分是:

// Message system is a duplex (read/write) stream
export class MessageSystem extends Duplex {
    constructor() {
        super({highWaterMark: 100, readableObjectMode: true, writableObjectMode: true});
    }
    public _read(size: number): void {
        var chunk = this.read();
        console.log(`Recieved ${chunk}`);
        this.push(chunk);
    }
    public _write(chunk: Message, encoding: string, 
        callback: (error?: Error | null | undefined, chunk?: Message) => any): void {
        if (chunk.data === null) {
            callback(new Error("Message.Data is null"));
        } else {
            callback();
        }
    }
}

export class SystemStream extends Transform {
    public type: MessageType = MessageType.Global;
    public data: Array<Message> = new Array<Message>();
    constructor() {
        super({highWaterMark: 100, readableObjectMode: true, writableObjectMode: true});
    }
    public _transform(chunk: Message, encoding: string, 
        callback: TransformCallback): void {
        if (chunk.single && (chunk.type === this.type || chunk.type === MessageType.Global)) {
            console.log(`Adding ${chunk}`);
            this.data.push(chunk);
            chunk = new Message(chunk.data, MessageType.Removed, true);
            callback(undefined, chunk); // TODO: Is this correct?
        } else if (chunk.type === this.type || chunk.type === MessageType.Global) { // Ours and global
            this.data.push(chunk);
            callback(undefined, chunk);
        } else { // Not ours
            callback(undefined, chunk);
        }
    }
}

export class EngineStream extends SystemStream {
    public type: MessageType = MessageType.Engine;
}

export class IOStream extends SystemStream {
    public type: MessageType = MessageType.IO;
}

let ms = new MessageSystem();
let es = new EngineStream();
let io = new IOStream();

let pipeline = promisify(Stream.pipeline);

async function start() {
    console.log("Running Message System");
    console.log("Writing new messages");
    ms.write(new Message("Hello"));
    ms.write(new Message("world!"));
    ms.write(new Message("Engine data", MessageType.Engine));
    ms.write(new Message("IO data", MessageType.IO));
    ms.write(new Message("Order matters in the pipe, even if Global", MessageType.Global, true));
    ms.end(new Message("Final message in the stream"));
    console.log("Piping data");
    await pipeline(
        ms,
        es,
        io
    );
}

Promise.all([start()]).then(() => {
    console.log(`Engine Messages to parse: ${es.data.toString()}`);
    console.log(`IO Messages to parse: ${io.data.toString()}`);
});

输出应类似于:

Running message system
Writing new messages
Hello
world!
Engine Data
IO Data
Order Matters in the pipe, even if Global
Engine messages to parse: Engine Data
IO messages to parse: IO Data

任何帮助将不胜感激。谢谢!

注意:我用我的其他帐户发布了此信息,而不是我的实际帐户。对于重复的内容表示歉意。

编辑:我最初将存储库设为私有(private),但已将其公开以帮助澄清答案。更多用法可以在feature/inital_system branch上找到。 checkout 后可以使用 npm start 运行它。

编辑:为了冗长起见,我已将自定义流放在这里。我认为我比以前走得更好,但现在在管道中收到了一个“空”对象。

最佳答案

the documentation状态,stream.pipeline 是基于回调的,不会返回 promise 。

它有自定义的 promisified 版本,可以使用 util.promisify 访问:

const pipeline = util.promisify(stream.pipeline);

...

await pipeline(...);

关于node.js - NodeJS 流不等待异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54548500/

相关文章:

angular - 有条件地将 RouterLinkActive 属性停用为某个值

angular - 带有构造函数的 Typescript 接口(interface) - 如何实现?

javascript - 为什么 Chrome 在 "strict mode"中使用 block 内的函数时仍然保持沉默?

node.js - Mongoose 和 MongoDB,关系不同步

node.js - MongoDB:$lookup 返回空数组

angular - ngx-bootstrap - 输入的时间选择器弹出窗口

javascript - 如何捕获 fetch 的 then() 中的 json 文本

javascript - 单击返回到 Reactjs 中的先前状态或触发功能

javascript - 如何让 riak-js 返回行走的对象?

node.js - 为什么Node.js停止工作?