I am using Node.js 18.16.0 x64 on Windows 10 Pro 22H2 x64, I just encountered a strange bug that prevents me from using Node.js after importing readline.
I needed a way to get user input using only built-in and absolutely not any library that needs to be installed.
Any code that requires readline will trigger the bug.
I copy-pasted code from this answer:
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
});
readline.question(`What's your name?`, name => {
console.log(`Hi ${name}!`);
readline.close();
});
I get this:
Welcome to Node.js v18.16.0.
Type ".help" for more information.
> const readline = require('readline').createInterface({
... input: process.stdin,
... output: process.stdout,
... });
undefined
>
>
rreeaaddlliinnee..qquueessttiioonn((``WWhhaatt''ss yyoouurr nnaammee??``,, nnaammee ==>> {{
...
ccoonnssoollee..lloogg((``HHii $${{nnaammee}}!!``));;
...
rreeaaddlliinnee..cclloossee(());;
...
}}));;
Then after I press Enter node.exe immediately closes itself.
I also tried this
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function readLineAsync(message) {
return new Promise((resolve, reject) => {
rl.question(message, (answer) => {
resolve(answer);
});
});
}
// Leverages Node.js' awesome async/await functionality
async function demoSynchronousPrompt() {
var promptInput = await readLineAsync("Give me some input >");
console.log("Won't be executed until promptInput is received", promptInput);
rl.close();
}
Welcome to Node.js v18.16.0.
Type ".help" for more information.
> const readline = require('readline');
solve(answer);
undefined
>
> const rl = readline.createInterface({
... input: process.stdin,
... output: process.stdout
... });
undefined
>
>
ffuunnccttiioonn rreeaaddLLiinneeAAssyynncc((mmeessssaaggee)) {{
...
rreettuurrnn nneeww PPrroommiissee((((rreessoollvvee,, rreejjeecctt)) ==>> {{
...
rrll..qquueessttiioonn((mmeessssaaggee,, ((aannsswweerr)) ==>> {{
...
rree }}));;
...
}}));;
...
}}
undefined
>
>
//// LLeevveerraaggeess NNooddee..jjss'' aawweessoommee aassyynncc//aawwaaiitt ffuunnccttiioonnaalliittyy
undefined
>
aassyynncc ffuunnccttiioonn ddeemmooSSyynncchhrroonnoouussPPrroommpptt(()) {{
...
vvaarr pprroommppttIInnppuutt == aawwaaiitt rreeaaddLLiinneeAAssyynncc((""GGiivvee mmee ssoommee iinnppuutt >>""));;
...
ccoonnssoollee..lloogg((""WWoonn''tt bbee eexxeeccuutteedd uunnttiill pprroommppttIInnppuutt iiss rreecceeiivveedd"",, pprroommppttIInnppuutt));;
...
rrll..cclloossee(());;
...
}}
Same thing happens.
What is going on?