1
function readTextFile(filename, callback){
    var fs = require('fs');
    fs.readFile(filename, 'utf8', function(err, data){
        if(err){
            throw err;
        }else{
            callback(data);
        }
    });
}

var set1 = [];
var set2 = [];
var set3 = [];
var set4 = [];
var set5 = [];

readTextFile("./data/names.json", function(text){
    var names = JSON.parse(text);
    set1 = names.prop1.prop2;
    set2 = names.prop1.prop3;
    set3 = names.prop1.prop4;
    set4 = names.prop5.prop2;
    set5 = names.prop5.prop3;
});
console.log(set1);

Running this section of code, using "node jsonRead.js" returns [ ] for any array called in console.log(). This section of code used to work about 80% of the time, but now it doesn't work at all, and I'm not sure why. I would appreciate any advice on how to get it working again.

Calvin D.
  • 21
  • 1
  • 2
    I think this has been answered here - http://stackoverflow.com/questions/10058814/get-data-from-fs-readfile – CD-jS May 19 '16 at 15:51
  • isn't that asynchronous code? readTextFile() returns immediately, which means `set1` will not yet have been populated. – Marc B May 19 '16 at 15:52
  • [Why is my variable unaltered after I modify it inside of a function?](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Jonathan Lonowski May 19 '16 at 16:12
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Oct 25 '18 at 12:00

2 Answers2

1

maybe the read process is still going on.

try the console.log(set1); in the callback:

readTextFile("./data/names.json", function(text){
    var names = JSON.parse(text);
    set1 = names.prop1.prop2;
    set2 = names.prop1.prop3;
    set3 = names.prop1.prop4;
    set4 = names.prop5.prop2;
    set5 = names.prop5.prop3;

    console.log(set1);
});

This is cause the callbackfunction of readTextFile is executed when reading finished, whereas the other code is executed as written.

You could solve this by using Promises. Checkout the q library for example: https://github.com/kriskowal/q

chresse
  • 5,486
  • 3
  • 30
  • 47
1

Node.js paradigm of executing code is Asynchronous , means it will execute next line of code after calling async method . In your above example readTextFile is called and execution will continue to next line . It will not wait for return .

Sumeet Kumar Yadav
  • 11,912
  • 6
  • 43
  • 80
  • How can I make the function return the data I need exactly when I need it, while still keeping it asynchronous? – Calvin D. May 19 '16 at 21:19