Created
April 22, 2024 01:21
-
-
Save swax/964a2488494048c8e03d05493d9370f8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Unexpeced readline behavior in node.js: | |
* | |
* Let the first prompt time out | |
* Enter a value in the second prompt | |
* Enter a value in the third prompt | |
* The third prompt should hang and time out (unless terminal is set to false) | |
* | |
* Even without the abort at all it has the same behavior, not processing input. | |
* Setting terminal to `false` in createInterface() makes it work as expected | |
*/ | |
import * as readline from "readline"; | |
function getInput() { | |
return new Promise((resolve) => { | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout, | |
terminal: true, | |
}); | |
const controller = new AbortController(); | |
const timeout = setTimeout(() => { | |
controller.abort(); | |
rl.close(); | |
resolve("TIMEOUT"); | |
}, 5000); | |
rl.question("prompt> ", { signal: controller.signal }, (answer) => { | |
clearTimeout(timeout); | |
rl.close(); | |
resolve(answer); | |
}); | |
}); | |
} | |
while (true) { | |
const input = await getInput(); | |
console.log("You entered: ", input); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment