So I'm trying out readlineSync to get user input (saw it was the best option to get user input). But then it doesn't output to the console. And it breaks out of node as soon as its done running. Help me out.
var readlineSync = require("readline-sync");
var firstName = readlineSync.question("First Name:");
console.log("Hi" + firstName);
"Expected Output: Hi Ifeoluwa"
"Actual result: Undefined and node exits automatically"
Node Console
So I'm trying out readlineSync to get user input (saw it was the best option to get user input). But then it doesn't output to the console. And it breaks out of node as soon as its done running. Help me out.
var readlineSync = require("readline-sync");
var firstName = readlineSync.question("First Name:");
console.log("Hi" + firstName);
"Expected Output: Hi Ifeoluwa"
"Actual result: Undefined and node exits automatically"
Node Console
Share Improve this question edited Jun 16, 2019 at 17:05 CFCIFE asked Jun 16, 2019 at 16:42 CFCIFECFCIFE 1321 gold badge1 silver badge12 bronze badges 3- Seems like it may be an issue between the library and node's REPL. If you run it from a file, it will work – Alberto Rivera Commented Jun 16, 2019 at 17:02
-
Create a new folder. Run
npm init
, and select all your options. Runnpm install --save readline-sync
. Create a new file (sayindex.js
) and paste your code in there. Runnode index.js
or the name of your file. – Alberto Rivera Commented Jun 16, 2019 at 17:10 - @AlbertoRivera I'd try that out now. Thanks – CFCIFE Commented Jun 16, 2019 at 17:10
2 Answers
Reset to default 1The library does not work inside the REPL.
There is a line within the source code that reads:
if (process.stdin.isTTY) {
process.stdin.pause();
try {
fdR = fs.openSync('/dev/tty', 'r'); // device file, not process.stdin
ttyR = process.stdin._handle;
} catch (e) { /* ignore */ }
}
The process.stdin.pause
will stop your current REPL session. However, when run from a file, the library works well.
i've read the documantion and it's working as expected, try to put the code to this sandbox
const express = require("express");
const app = express();
const readlineSync = require('readline-sync');
// Wait for user's response.
var userName = readlineSync.question('May I have your name? ');
console.log('Hi ' + userName + '!');
server.listen(3000, () => {
console.log(`Server is running`);
});