NodeJS流不等待异步

时间:2019-02-06 07:24:21

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

在测试NodeJS流时遇到了一个问题。我似乎无法让我的项目在运行stream.pipeline之后等待双工和Transform流的输出,即使它正在返回承诺。也许我缺少了一些东西,但是我相信脚本应该在继续操作之前等待函数返回。我要开始工作的项目中最重要的部分是:

// 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

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

注意:我用其他帐户发布了该帐户,而不是我的实际帐户。道歉的重复。

编辑:最初,我有私有的repo,但是为了帮助弄清答案,已经公开了。在feature/inital_system branch上可以找到更多用法。检出时可以与npm start一起运行。

编辑:我已经将自定义流放在此处以进行详细说明。我认为我的状态比以前更好,但是现在在管道中收到了一个“空”对象。

2 个答案:

答案 0 :(得分:2)

the documentation指出,stream.pipeline是基于回调的,不会返回承诺。

它具有可通过util.promisify访问的自定义承诺版本:

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

...

await pipeline(...);

答案 1 :(得分:0)

经过几天的努力,我找到了答案。问题是我对Duplex流的实现。此后,我将MessageSystem更改为Transform流,以便于管理和使用。

这是产品:

export class MessageSystem extends Transform {
    constructor() {
        super({highWaterMark: 100, readableObjectMode: true, writableObjectMode: true});
    }
    public _transform(chunk: Message, encoding: string,
        callback: TransformCallback): void {
            try {
                let output: string = chunk.toString();
                callback(undefined, output);
            } catch (err) {
                callback(err);
            }
        }
}

感谢@estus进行快速回复并进行检查。再次,我一直在API中找到答案!

可以在this repository中找到我的发现的存档库。