繁体   English   中英

组合readline和puppeteer时,在console.log中阻止进程

[英]Process blocked at console.log when combining readline and puppeteer

以下代码将在console.log("this line.....");之前永久阻止console.log("this line.....");

const puppeteer = require('puppeteer');
const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
async function main() {
    browser = await puppeteer.launch();
    rl.close();
    await browser.close();  
    console.log("this line will not be executed.");
}
main();

console.log下面移动rl.close()解决了这个问题,删除了browser = .....await browser.close()做了同样的事情。

这是木偶戏的错吗? 还是有一些我不明白的机制?

Puppeteer版本:1.11.0
Node.js版本:10.14.2
操作系统:Windows 10 1803

似乎值得向puppeteer GitHub存储库报告这个问题。 在这个组合之后,stdin和事件循环发生了一些非常奇怪的事情(Chrome确实退出,但Node.js仍然存在,并且在Ctrl + C中止后,Windows shell中的提示出现两次,就像ENTER被缓冲直到退出一样)。

FWIW,如果readline.createInterface() terminal选项设置为false ,则此问题将消失。

看起来你并不完全理解ASYNC / AWAIT在js中是如何工作的。

如果在异步函数中使用await ,它将暂停异步函数并等待Promise在继续之前解析。

异步函数中的代码将被一致地处理,就像它是同步的一样,但不会阻塞主线程。

async function main() {
    browser = await puppeteer.launch(); // will be executed first
    rl.close();// will be executed second (wait untill everithing above is finished)
    await browser.close(); // will be executed third (wait untill everithing above is finished)
    console.log("this line will not be executed."); // will be executed forth (wait untill everithing above is finished)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM