0

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.

3
  • Have you ever heard about functional programming, asynchronous operations and so on? This is how it works indeed. Commented Feb 9, 2016 at 20:17
  • @skypjack, 15 years of java did it. :-( started on node a couple of weeks back. :-) Commented Feb 9, 2016 at 20:20
  • The problem is that the callback function is not executed immediately, not Array.push(). Add some prefixes to your console.log messages and note the order they are printed. Commented Feb 9, 2016 at 20:22

1 Answer 1

2

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);
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.