user1424739
user1424739

Reputation: 13655

The correct way to read from stdin in nodejs

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.

Upvotes: 4

Views: 5040

Answers (2)

Brenn
Brenn

Reputation: 1384

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}`);
}

Upvotes: 3

Evan Shortiss
Evan Shortiss

Reputation: 1658

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

Upvotes: 2

Related Questions