How to Read from stdin in JavaScript

In javascript (nodejs anyway) stdin can be read as a stream of bytes. Therefore you need to tell node which encoding it is (utf-8 in our instance). We do the reads on the readable event, and read as much data as we can and print it to stdout.

process.stdin.setEncoding("utf8");

process.stdin.on("readable", function () {
  var chunk = process.stdin.read();
  if (chunk !== null) {
    process.stdout.write(chunk);
  }
});

Related Posts