最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use readlineSync on Nodejs - Stack Overflow

programmeradmin1浏览0评论

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. Run npm install --save readline-sync. Create a new file (say index.js) and paste your code in there. Run node 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
Add a ment  | 

2 Answers 2

Reset to default 1

The 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`);
});
发布评论

评论列表(0)

  1. 暂无评论