Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C scanf equivalent in nodejs

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
    }
});
like image 738
Oleksandr T. Avatar asked Dec 04 '22 00:12

Oleksandr T.


1 Answers

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.

like image 195
user7116 Avatar answered Dec 05 '22 15:12

user7116