Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js: readSync from stdin?

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 
like image 886
panzi Avatar asked Aug 07 '10 15:08

panzi


People also ask

How do I stop a process from using Stdin?

`process. stdin. pause` will "close" `stdin`.

How to import readline in NodeJS?

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.

What is process Stdin in NodeJS?

The stdin property of the process object is a Readable Stream. It uses on() function to listen for the event. Syntax: process.


2 Answers

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.

like image 146
dhruvbird Avatar answered Sep 22 '22 23:09

dhruvbird


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

like image 25
Marcus Pope Avatar answered Sep 25 '22 23:09

Marcus Pope