Is it possible to synchronously read from stdin in node.js? Because I\'m writing a brainfuck to JavaScript compiler in JavaScript (just for fun). Brainfuck supports a read o
Important: I've just been informed by a Node.js contributor that .fd is undocumented and serves as a means for internal debugging purposes. Therefore, one's code should not reference this, and should manually open the file descriptor with fs.open/openSync
.
In Node.js 6, it's also worth noting that creating an instance of Buffer
via its constructor with new
is deprecated, due to its unsafe nature. One should use Buffer.alloc
instead:
'use strict';
const fs = require('fs');
// small because I'm only reading a few bytes
const BUFFER_LENGTH = 8;
const stdin = fs.openSync('/dev/stdin', 'rs');
const buffer = Buffer.alloc(BUFFER_LENGTH);
fs.readSync(stdin, buffer, 0, BUFFER_LENGTH);
console.log(buffer.toString());
fs.closeSync(stdin);
Also, one should only open and close the file descriptor when necessary; doing this every time one wishes to read from stdin results in unnecessary overhead.