4

https://github.com/nodejs/node/issues/7439

The above page shows that fs.readFileSync(process.stdin.fd) does not work correctly.

Is fs.readFileSync(fs.openSync('/dev/stdin', 'rs')) the correct way to read from stdin? But it seems that it only works in certain cases, but not all case.

I am wondering what is the correct way to read from stdin in nodejs.

2 Answers 2

3

You can use readline

https://nodejs.org/api/readline.html

from those docs:

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

and to read lines:

for await (const line of rl) {
  // Each line in input.txt will be successively available here as `line`.
  console.log(`Line from file: ${line}`);
}
Sign up to request clarification or add additional context in comments.

Comments

2

The process global has a stdin interface. This will log a line after a user enters text and presses Enter on the keyboard.

let buffer = ''
process.stdin.resume()
process.stdin.on('data', (d) => buffer = buffer.concat(d.toString()))

setTimeout(() => {
    // Exit after 5 seconds and print entered content
    console.log(buffer.toString('utf8'))
    process.exit(0)
}, 5000)

Docs - https://nodejs.org/api/process.html#process_process_stdin

4 Comments

I want to read the whole stdin into a single string. Will this read the whole stdin?
Check my updated answer. It shows how you can capture all input for 5 seconds. Remove the setTimeout for whatever you're doing, I just put it there as an example.
If the input takes more than 5 sec to process, what will happen?
Just remove the timeout. It was an example to force the program to close. Without it it will keep reading until some condition you define is triggered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.