0

this code

var fs = require("fs");
var freeApps = readFile();
console.log('4' + freeApps.toString());

function readFile () {
    var content = '';
    fs.readFile(__dirname + "/public/json/" + "test.json", function(err, data) {
        if (err) {
            console.error(err);
            return '';
        }
        console.log('1' + data.toString());
        content = data;
        console.log('2' + content.toString());
    });
    console.log('3' + content.toString());
    return content;
}

returns

3
4
1{"application":[{"name":"test","test":"name"}]}
2{"application":[{"name":"test","test":"name"}]}

where the letter is the test.json content. How could I properly read a file content and deal with it within the function ? I succed to get the content at where 1 is and forward to another function but not within the function why is that ?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user3732793
  • 1,699
  • 4
  • 24
  • 53
  • 2
    ***a...synch...ronous***, one can not simply return from something that has happened yet. – adeneo Sep 29 '16 at 18:43
  • It is like ordering a pizza, you need to wait for it to be delivered before you can use it. You can not return from an asynchronous method. – epascarello Sep 29 '16 at 18:44
  • I was afraid so. how can I read a file without blocking the whole app ? – user3732793 Sep 29 '16 at 18:45
  • You can read a file and not block the whole app, you just can't expect the answer before it's done reading. So in a way, you HAVE to block somewhere. – ZekeDroid Sep 29 '16 at 18:46
  • Exactly like you did. You just have to make `readFile` accept a callback or return a promise. – Felix Kling Sep 29 '16 at 18:46

1 Answers1

2

If you asking why your readFile function doesn't return content, which is likely since this code is off, it's because the return statement is called before the file is finished reading. This is called an "asynchronous" function because it runs in parallel with the rest of your code.

Therefore, you can't reassign content like you do here. Instead, you would need to call a function from within your callback (where your console logs 1 and 2 are) and/or make use of Promises, which are an advanced technique used to handle asynchronous behavior.

ZekeDroid
  • 7,089
  • 5
  • 33
  • 59