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 operation which needs to be implemented synchronously.
I tried this:
const fs = require('fs');
var c = fs.readSync(0,1,null,'utf-8');
console.log('character: '+c+' ('+c.charCodeAt(0)+')');
But this only produces this output:
fs:189
var r = binding.read(fd, buffer, offset, length, position);
^
Error: EAGAIN, Resource temporarily unavailable
at Object.readSync (fs:189:19)
at Object.<anonymous> (/home/.../stdin.js:3:12)
at Module._compile (module:426:23)
at Module._loadScriptSync (module:436:8)
at Module.loadSync (module:306:10)
at Object.runMain (module:490:22)
at node.js:254:10
An updated version of Marcus Pope's answer that works as of node.js v0.10.4:
Please note:
2 - Unstable
as ofnode.js v0.10.4
.OS X 10.8.3
andWindows 7
: the major difference is: synchronously reading interactive stdin input (by typing into the terminal line by line) only works on Windows 7.Here's the updated code, reading synchronously from stdin in 256-byte chunks until no more input is available:
Have you tried:
However, it will wait for the ENTIRE file to be read in, and won't return on \n like scanf or cin.
I found a library that should be able to accomplish what you need: https://github.com/anseki/readline-sync
I wrote a little C++ add-on module that make synchronous reading on keyboard (https://npmjs.org/package/kbd).