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
scanfand thedataevent 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:
Given how
inputthen contains your data you’ll need to use some method to extract the string of interest and then useparseInt. Perhaps a naive approach to your problem, assuming 1 integer perinput: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.