-1

I have been starting to learn the basics of "fs" on node.js, and ran into a small problem that I am not sure how to fix. I declare a variable in the first function, but try to change it in the second. I know that this will not update the value in the nested function, however, I am not sure how I can get it from the second function to return it with the first function.

Code:

function fetchUserData(id,fetchedData){
    var returnValue
    fs.readFile("./mainData.json","utf-8",(err,jsonString) => {
        if (err) {
            console.log("Error while retrieving data: " + err);
        } else {
            try {
                const currentData = JSON.parse(jsonString);
                if (currentData) {
                    if (currentData["User" + id]){
                        returnValue = [currentData, true];
                    } else {
                        returnValue = [currentData, false];
                    }
                }
            } catch(err) {
                console.log("Error while parsing data to read: " + err);
            };
        };
    });
    return returnValue;
};
  • 1
    Use a `Promise` or readFileSync – John Apr 10 '21 at 00:26
  • `fs.readFile()` is non-blocking and asynchronous. That means it calls its callback sometime LATER after `fs.readFile()` returns and thus your `return returnValue` executes before `returnValue` has a value. See the question yours was marked a duplicate of. In Javascript, you must communicate back an asynchronously-retrieved value by returning a promise, using a callback like `fs.readFile()` does or building some sort of event notification. Those are your main choices. In this case, you should probably use `fs.promises.readFile()` and return the promise that that already creates. – jfriend00 Apr 10 '21 at 00:54

1 Answers1

0

The problem is not in the variable, but in execution sequence. readFile is asynchronous function, the third argument is a callback to be executed later. Yes, it eventually updates outer variable in the closure but outer function doesn't have a chance to pick it because it already returned.

You should either use syncronous readFileSync (this looks best for your case), OR create a Promise object which is resolved on callback completion.

Vasily Liaskovsky
  • 2,248
  • 1
  • 17
  • 32
  • The OP could also use the promisified versions of the `fs` methods using the [`fs/promises`](https://nodejs.org/api/fs.html#fs_promises_api) API. – Arun Kumar Mohan Apr 10 '21 at 00:46