0

I am trying to read a file and I want that logic to be inside a function, I did - that is below, I see I should get the result in terms of promise object, but I am not sure, the below code output undefined. Please tell how to fix this one ?

 var fs = require('fs');


 function readAppData() {
        var content;
        fs.readFile('app-lock.json', function read(err, data) {
            if (err) {  console.log(err); }
            try {

                content = JSON.parse(data);
            } catch (err) {
                console.log(err);
            }
        }).then(t => {return content});

    }

    console.log(readAppData())
ajayramesh
  • 3,576
  • 8
  • 50
  • 75
  • 1
    This is not how to use promises. Seems like you dont want to have async file reading. the FS library supports sync calls: `fs.readFileSync` – Shane Jul 29 '17 at 16:20

1 Answers1

1

You may want to await the promise that was made:

function readAppData() {
    return new Promise(function(res,thr){
    fs.readFile('app-lock.json', function read(err, data) {
        if (err) { thr(err);}
        try {
            res(JSON.parse(data));
        } catch (err) {
            thr(err);
        }
    })
    })
}

(async function(){
   console.log(await readAppData())
})()
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • this one works, I prefer to get the return object like this `readAppData() .then(data=>{console.log(data)}, err=> {console.log(err)});` – ajayramesh Jul 29 '17 at 16:39