8

I'd like to teach students how to program using JavaScript. I don't want to introduce new students to call-backs or any other complex program structure. Looking at Node.js the readline used for standard input uses a call-back. For simple input data, then do a calculation, I'd like a simple equivalent to an input like Python or other similar languages have:

width = input("Width? ")
height = input("Height? ")
area = width * height
print("Area is",area)

Is there some way to do this with JavaScript?

Jorge Bucaran
  • 5,588
  • 2
  • 30
  • 48
Paul Vincent Craven
  • 2,027
  • 3
  • 19
  • 24
  • If you teach CS, you may be interested in the new [CS Educator's Stack Exchange](http://cseducators.stackexchange.com) (though since it's still in private beta, it's easiest to enter [through here](https://area51.stackexchange.com/proposals/92460/computer-science-educators)) – Ben I. Jun 02 '17 at 19:17

2 Answers2

8

The module readline-sync, (source can be found here, npm page here) will do what you want, it looks like.

If you'd prefer to work at a lower level, it looks like it works by passing the stdin file descriptor (stdin.fd) to the synchronous fs methods. For example:

fs.readSync(stdin.fd, buffer, 0, BUF_SIZE)
Aaron Dufour
  • 17,288
  • 1
  • 47
  • 69
4

There is sget as well, a simpler and bit saner module I wrote that accomplishes what the OP is asking for.

var sget = require('./sget');

var width = sget('Width?'),
    height = sget('Height?'),
    area = width * height;

console.log('Area is', area);
Jorge Bucaran
  • 5,588
  • 2
  • 30
  • 48