11

Put in another way, what is the node.js equivalent of C's getchar function? (which waits for input and when it gets it, it returns the character code of the letter, and subsequent calls get more characters from stdin)

I tried searching google, but none of the answers were synchronous.

phillips1012
  • 368
  • 4
  • 10
  • See this answer http://stackoverflow.com/a/9742711/1048697 – Bulkan Nov 25 '13 at 06:13
  • 1
    @Bulkan that only works for files being piped into the script. The accepted answer for that question will work better: http://stackoverflow.com/a/8452997/893780 – robertklep Nov 25 '13 at 08:15
  • 1
    You need to set `stdin.setRawMode(true);` Have a look at this answer for a complete example: https://stackoverflow.com/a/12506613/771431 – xonya Apr 26 '19 at 16:57

1 Answers1

2

Here is a simple implementation of getChar based fs.readSync:

fs.readSync(fd, buffer, offset, length)

Unlike the other answer, this will be synchronous, only read one char from the stdin and be blocking, just like the C's getchar:

let fs = require('fs')

function getChar() {
  let buffer = Buffer.alloc(1)
  fs.readSync(0, buffer, 0, 1)
  return buffer.toString('utf8')
}

console.log(getChar())
console.log(getChar())
console.log(getChar())
Anthony Garcia-Labiad
  • 3,531
  • 1
  • 26
  • 30
  • WIth this method, I got following error, any idea? Error: EAGAIN: resource temporarily unavailable, read at Object.readSync (node:fs:611:3) – Jianwu Chen Jul 04 '21 at 16:01
  • Looks like stdin is not available - I'm assuming you're testing this code in interactive mode (with `node -i`)? It will not work when executed like this, but will work when doing `node script.js` or `echo "input" | node script.js`. – Anthony Garcia-Labiad Jul 05 '21 at 11:24
  • For me, this indeed reads one char, but only after the user pressed "enter" and stdin contains the entire line. Is there a way to get a char right after the user presses it? – dbkk Jul 12 '23 at 18:02