Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  156] [ 2]  / answers: 1 / hits: 15138  / 12 Years ago, wed, january 9, 2013, 12:00:00

If I want to read from the input stream in C I write scanf., Is there equivalent method in NodeJS to do the same?



For example, here's the code in C



int n,
m,
i;

scanf(%d, &n);

for (i = 0; i < n; i++) {
scanf(%d, &m);

............

}


Here's where I'm starting from in Node... TODO indicates where I'm stuck:



process.stdin.resume();
process.stdin.setEncoding(ascii);

process.stdin.on(data, function (input) {
var n = +input;
for (var i = 0; i < n; i++) {
// TODO
}
});

More From » node.js

 Answers
5

For starters, calling scanf and the data event for a readable stream in NodeJS are not equivalent. In the NodeJS example, you will need to parse the chunk of the input you've received.



You can examine how these chunks are sent to you by replacing the body of your on method with a simple:



process.stdout.write('onData: ' + input + 'n');


Given how input then contains your data you'll need to use some method to extract the string of interest and then use parseInt. Perhaps a naive approach to your problem, assuming 1 integer per input:



var n = 0;
var m = 0;
var state = 0;
process.stdin.on('data', function (input) {
switch (state)
{
case 0:
// we're reading 'n'
n = parseInt(input.trim(), 10);
state++;
break;

default:
// we're reading 'm'
m = parseInt(input.trim(), 10);

if (state++ == n)
{
// we've read every 'm'
process.exit();
}
break;
}
});


I'm not a terribly large fan of this means of getting data to your NodeJS event loop, you should instead look to command line arguments, configuration/input files, or some other means.


[#80981] Tuesday, January 8, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckenna

Total Points: 445
Total Questions: 109
Total Answers: 109

Location: Virgin Islands (U.S.)
Member since Sun, May 16, 2021
3 Years ago
;