as3rdaccount
as3rdaccount

Reputation: 3931

Nodejs how to have an api call read a file asynchrnously

This is my first nodejs project and I am still trying to get the hang of asynchronous calls so please bear with me. So in my routes I have registered '/users/username' to a function which will read a file (ideally a database but for now I am reading from a file). Now I have an option to call fs.readFileSync which I want to avoid. How do I pass a callback to fs.readFile which will then send the response back to the client?

Code:

var getData = function(key){
    try {
            fs.readFile(__dirname + '/users.json', function(err, tenantsJSON){
            var parsedConfig = JSON.parse(tenantsJSON.toString());
            if (!parsedConfig.hasOwnProperty(key)){
                throw {
                    name: key + "NotFound",
                    error: "key " + "does not exist.",
                    status: 404
                }
            }
            return parsedConfig[key] //How do I pass the response from here
        });

    } catch (e) {
        console.error(String.format("File {0} not found or is invalid: {1}",'config.json', e.message));
        throw {
            name: "Internal server error",
            error: "Internal server error",
            status: 500
        }
    }
}

In routes:

router.get('/users/:username', auth, function(req, res, next) {

     ///How do I get the read file back here?? 
      var body = getData(req.params.username);
})

Upvotes: 0

Views: 2010

Answers (1)

Gergo Erdosi
Gergo Erdosi

Reputation: 42038

You can make it asynchronous by passing a callback to getData():

var getData = function(key, callback) {

You then call this callback in readFile():

fs.readFile(__dirname + '/users.json', function(err, tenantsJSON) {
    if (err) {
        return callback(err);
    }

    // ...
    callback(null, parsedConfig[key]);
});

Then in the router:

router.get('/users/:username', auth, function(req, res, next) {

    getData(req.params.username, function (err, body) {
         // ...
         next();
    });
});

Upvotes: 1

Related Questions