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
`process. stdin. pause` will "close" `stdin`.
The following simple example illustrates the basic use of the node:readline module. import * as readline from 'node:readline/promises'; import { stdin as input, stdout as output } from 'node:process'; const rl = readline. createInterface({ input, output }); const answer = await rl. question('What do you think of Node.
The stdin property of the process object is a Readable Stream. It uses on() function to listen for the event. Syntax: process.
Have you tried:
fs=require('fs'); console.log(fs.readFileSync('/dev/stdin').toString());
However, it will wait for the ENTIRE file to be read in, and won't return on \n like scanf or cin.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With