Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read a single character from stdin synchronously?

Tags:

node.js

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.

like image 756
phillips1012 Avatar asked Nov 25 '13 05:11

phillips1012


People also ask

How will you read a single character from keyboard?

Correct option - D getchar Explanation:-Reading a single character can be done by using the function getchar .

How do you read a single character in Python?

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.

What is Javascript Stdin?

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.


1 Answers

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())
like image 115
Anthony Garcia-Labiad Avatar answered Oct 18 '22 20:10

Anthony Garcia-Labiad