ZumiKua
ZumiKua

Reputation: 506

Process blocked at console.log when combining readline and puppeteer

The following code will be blocked forever before 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();

Moving rl.close() below of console.log solves this problem, removing browser = ..... and await browser.close() did the same.

Is this a bug of puppeteer? Or does there are some mechanism I don't understand?

Puppeteer version: 1.11.0
Node.js version: 10.14.2
OS: Windows 10 1803

Upvotes: 3

Views: 648

Answers (2)

vsemozhebuty
vsemozhebuty

Reputation: 13782

It seems this is worth to be reported as an issue to the puppeteer GitHub repository. Something really weird happens to stdin and event loop after this combination (Chrome does exits, but the Node.js remains, and after the Ctrl+C abort the prompt appears twice in the Windows shell as if ENTER was buffered till the exit).

FWIW, this issue disappears if terminal option of readline.createInterface() is set to false.

Upvotes: 1

Igor Litvinovich
Igor Litvinovich

Reputation: 2502

It seems like you do not completely understand how ASYNC/AWAIT works in js.

If you use await inside an async function it will pause the async function and wait for the Promise to resolve prior to moving on.

A code inside your async function will be processed consistently as if it were synchronous, but without blocking the main thread.

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)
}

Upvotes: 0

Related Questions