0

I am trying to read a file using fs.readFile() and then use the result in the code that follows. The read process has to be asynchronous. Here is what I have so far:

var file = async () => {
  await fs.readFile(__dirname + "/file.json", "utf-8", (err, data) => {
    if (err) throw err
    return JSON.parse(data)
  })
}
console.log(file());

For some reason this code always logs undefined. Is there any way to do this without moving the console.log statement inside the readFile callback?

Wais Kamal
  • 5,858
  • 2
  • 17
  • 36
  • In your code above the `file` variable is a function. Specifically it is the function `async () ...`. Your code is similar to writing `async function file () { ... }`. That is, `file` is the NAME OF THE FUNCTION – slebetman May 18 '21 at 14:10
  • So where should the `async` go? Because even `console.log(file())` does not work. – Wais Kamal May 18 '21 at 14:11
  • The `async` keyword just makes the function return a Promise. So your `file` function will return a Promise. – slebetman May 18 '21 at 14:13
  • Ooh, ok. So how do I get the file data asynchronously? – Wais Kamal May 18 '21 at 14:16
  • You should wait for the result before logged it, const result = await file(); console.log(result) – Yoandry Collazo May 18 '21 at 14:24

2 Answers2

2

notable modifications : fs.promises.readFile => if you dont use promises dont use await. it you do use promises => dont use callback.

async function readFile() {
  const data = await fs.promises.readFile(__dirname + "/file.json", "utf-8");
  return JSON.parse(data)
}

(async() => {
  console.log(await readFile());
})();

for a synchronous version see others comments. (but i prefer async for performance reasons)

Raphael PICCOLO
  • 2,095
  • 1
  • 12
  • 18
1

Use Promise

const someFunction = async () => {
    try {
        var file = () => {
            return new Promise((resolve, reject) => {
                fs.readFile(__dirname + "/file.json", "utf-8", (err, data) => {
                    if (err) reject(err)
                    else resolve(data)
                })
            })
            
        }
        console.log(await file()); // this is the key
    } catch (err) {
        console.log(err)
    }
}

You need to add a try-catch block to catch the reject promise or any error that thrown. So it is better.

Or the older function style

async function someFunction() {
    // the contents are the same
    // ...
}

The problem is, the file() runs asynchronously and the code is not waiting for the result. Put await on the fs.readFile() function doesn't mean await the file() variable to finish its execution.

alramdein
  • 810
  • 2
  • 12
  • 26