6

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
    }
});
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144

3 Answers3

14

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.

user7116
  • 63,008
  • 17
  • 141
  • 172
3

Check sget.

var sget = require('./sget');

var width = sget('Width?'),
    height = sget('Height?'),
    area = width * height;

console.log('Area is', area);
Jorge Bucaran
  • 5,588
  • 2
  • 30
  • 48
2

This function will do what you asked for:

function readNums(s) {
   // Split it up into numbers and spaces
   var array = s.split(/(\d+)/);

   // Keep just the numbers
   array = array.filter(function(i) {return "" + +i == i});

   // Convert back to a number
   array = array.map(function(i) {return +i});

   // How many elements should there have been?
   var maxLen = array.shift();

   if (array.length < maxLen) {
     throw "Not enough enough numbers";
   } else {
     array.length = maxLen;
   }


   return array; 
}

console.log(readNums("4 10 20 30 40 50 60 70"));

Result:

[10, 20, 30, 40] 
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74