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
}
});
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.
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