How can I write blocking in stdout with node.js?

前端 未结 5 550
走了就别回头了
走了就别回头了 2021-01-18 00:46

I\'m writing a node.js application which stdout is piped to a file. I\'m writing everything with console.log. After a while my Application reaches the 1GB Limit and stops. T

5条回答
  •  孤独总比滥情好
    2021-01-18 01:04

    Edit: as indicated by commenter, this solution has a problem. printResolver could be made into an array, but using top solution is much easier

    A synchronous print function that also works with pipes aka FIFO's, using Async/await. Make sure you always call "print" with "await print"

    let printResolver;
    process.stdout.on('drain', function () {
        if (printResolver) printResolver();
    });
    
    async function print(str) {
        var done = process.stdout.write(str);
        if (!done) {
            await new Promise(function (resolve) {
                printResolver = resolve;
            });
        }
    }
    

提交回复
热议问题