kmansoor
kmansoor

Reputation: 4345

node js array.push 'not' working

I'm sure making a silly mistake, but can't trace it. Have a simple script to read in a file of the form:

<option value="us">United States</option>

trying to create a new file of the form:

{"value":"us","name":"United States"}

The issue is jsonC.push(c) is not working and the array remains empty. The console.log(c) does print json representation, still the very next line jsonC.push(c) fails to have any effect on jsonC array and it remains empty.

Here is the code:

var fs = require('fs');
var readline = require('readline');

var src = 'country.txt';
var dest = 'country.json';

var re = /.+["](\w{2})["][>]([a-zA-Z ]+)[<][/].+/;
var jsonC = [];

readline.createInterface({
    input: fs.createReadStream(src), terminal: false
}).on('line', function(line) {
    var match;
    if ((match = re.exec(line)) !== null) {
      var c = {};
      c.value = match[1];
      c.name = match[2];

      console.log(c); // prints fine
      jsonC.push(c); // not adding to the array
   }
});

console.log(jsonC); // prints []
console.log(JSON.stringify(jsonC)); // prints []

This is a stand alone node.js v4.2.6 script running on Win 7.

Upvotes: 0

Views: 2551

Answers (1)

Tennyson H
Tennyson H

Reputation: 1716

The reason is because you are adding values to jsonC in an callback function. the readline.createInterface(...).on(function() { is a callback, and is not synchronous. So your program is just scheduling that function away, and then it does console.log(jsonC) and jsonC is still empty because the callback hasn't fired yet.

Try outputing the value in the callback, or using promises to know when the callback has finished.

Here is a working example using Promises:

function readFromFile() {
    var fsRead = Promise.defer();
    readline.createInterface({
        input: fs.createReadStream(src), terminal: false
    }).on('line', function(line) {
        var match;
        if ((match = re.exec(line)) !== null) {
          var c = {};
          c.value = match[1];
          c.name = match[2];
          jsonC.push(c);
          fsRead.resolve();
       }
    });
    return fsRead.promise();
}

readFromFile().then(function(result) {
    console.log(jsonC);
})

Upvotes: 2

Related Questions