12

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.

3

1 Answer 1

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())
Sign up to request clarification or add additional context in comments.

3 Comments

WIth this method, I got following error, any idea? Error: EAGAIN: resource temporarily unavailable, read at Object.readSync (node:fs:611:3)
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.
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?

Your Answer

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