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.
Correct option - D getchar Explanation:-Reading a single character can be done by using the function getchar .
Individual characters in a string can be accessed by specifying the string name followed by a number in square brackets ( [] ). String indexing in Python is zero-based: the first character in the string has index 0 , the next has index 1 , and so on.
stdin property is an inbuilt application programming interface of the process module which listens for the user input. The stdin property of the process object is a Readable Stream. It uses on() function to listen for the event.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With