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
An updated version of Marcus Pope's answer that works as of node.js v0.10.4:
Please note:
2 - Unstable
as of node.js v0.10.4
.OS X 10.8.3
and Windows 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:
var fs = require('fs');
var BUFSIZE=256;
var buf = new Buffer(BUFSIZE);
var bytesRead;
while (true) { // Loop as long as stdin input is available.
bytesRead = 0;
try {
bytesRead = fs.readSync(process.stdin.fd, buf, 0, BUFSIZE);
} catch (e) {
if (e.code === 'EAGAIN') { // 'resource temporarily unavailable'
// Happens on OS X 10.8.3 (not Windows 7!), if there's no
// stdin input - typically when invoking a script without any
// input (for interactive stdin input).
// If you were to just continue, you'd create a tight loop.
throw 'ERROR: interactive stdin input not supported.';
} else if (e.code === 'EOF') {
// Happens on Windows 7, but not OS X 10.8.3:
// simply signals the end of *piped* stdin input.
break;
}
throw e; // unexpected exception
}
if (bytesRead === 0) {
// No more stdin input available.
// OS X 10.8.3: regardless of input method, this is how the end
// of input is signaled.
// Windows 7: this is how the end of input is signaled for
// *interactive* stdin input.
break;
}
// Process the chunk read.
console.log('Bytes read: %s; content:\n%s', bytesRead, buf.toString(null, 0, bytesRead));
}
After fiddling with this for a bit, I found the answer:
process.stdin.resume();
var fs = require('fs');
var response = fs.readSync(process.stdin.fd, 100, 0, "utf8");
process.stdin.pause();
response will be an array with two indexes, the first being the data typed into the console and the second will be the length of the data including the newline character.
It was pretty easy to determine when you console.log(process.stdin)
which enumerates all of the properties including one labeled fd
which is of course the name of the first parameter for fs.readSync()
Enjoy! :D
Here is the implementation with `async await`. In the below code, the input is taken from standard input and after receiving data the standard input is stopped waiting for data by using `process.stdin.pause();`.
process.stdin.setEncoding('utf8');
// This function reads only one line on console synchronously. After pressing `enter` key the console will stop listening for data.
function readlineSync() {
return new Promise((resolve, reject) => {
process.stdin.resume();
process.stdin.on('data', function (data) {
process.stdin.pause(); // stops after one line reads
resolve(data);
});
});
}
// entry point
async function main() {
let inputLine1 = await readlineSync();
console.log('inputLine1 = ', inputLine1);
let inputLine2 = await readlineSync();
console.log('inputLine2 = ', inputLine2);
console.log('bye');
}
main();
I wrote this module to read one line at a time from file or stdin. The module is named as line-reader
which exposes an ES6 *Generator function
to iterate over one line at a time. here is a code sample(in TypeScript) from readme.md.
import { LineReader } from "line-reader"
// FromLine and ToLine are optional arguments
const filePathOrStdin = "path-to-file.txt" || process.stdin
const FromLine: number = 1 // default is 0
const ToLine: number = 5 // default is Infinity
const chunkSizeInBytes = 8 * 1024 // default is 64 * 1024
const list: IterableIterator<string> = LineReader(filePathOrStdin, FromLine, ToLine, chunkSizeInBytes)
// Call list.next to iterate over lines in a file
list.next()
// Iterating using a for..of loop
for (const item of list) {
console.log(item)
}
Apart from above code, you can also take a look at src > tests
folder in the repo.
Note:-
line-reader module doesn't read all stuff into memory instead it uses generator function to generate lines async or sync.
I found a library that should be able to accomplish what you need: https://github.com/anseki/readline-sync