fs.writeFile() seems to not be running the callback suddenly

Sun Tzu, a Chinese military general and strategist, famously known as the author of Art of War, once said

If your code works perfectly, it’s best not to touch it. :grinning:



Here’s my take on the whole thing:

You mentioned that your function wasn’t commenting properly, but what if the file was written and something held up the callback, preventing the comment? More on the blocking below.

As @wh0 mentions above, nesting your writeFile in a promise, which is also nested in an async function, is heavily unnecessary. Keeping the original async saveFile function, I’d recommend

const fs = require('fs').promises;

async function saveFile(filename, obj, comment) {
  try {
    await fs.writeFile(filename, JSON.stringify(obj, null, 2))

    if (comment != null && comment != "" && comment != undefined) {
    // or if (comment), which is the same thing
      console.log(comment);
    }
  } catch (err) {
    // console.error(err)
    throw err
  } 

  return;
}

Alternatively, suppose you’d like to use the original writeFile code. In that case, you should run it in a normal synchronous function, as in function saveFile without the async, which @wh0 once again rightfully points out.

Let’s talk about writeFile and writeFileSync.

writeFile is asynchronous, meaning it will run when it gets a chance while your program continues to do other stuff - we call this “non-blocking”.

On the other hand, writeFileSync is synchronous and blocking, which means that your program is going to “stop the car, stop everything, focus on the file write and nothing else”. This pauses the execution of the program to ensure your file gets written, before moving onto the rest of the program. It’s also faster, but at the cost of pausing execution. You won’t really notice the difference between writeFileSync and writeFile, especially in terms of speed and blocking, unless you’re dealing with large files.

I would strongly recommend avoiding writeFileSync, especially if you’re dealing with multiple file writes, especially on a (Node) server. I remember a StackOverflow post that said writeFile would be faster if you did not wait for the callback, but I’m unable to verify this claim.

Whether 24kB is a large file or not is up for debate. For reference, 500 placeholder comments is roughly around 41kB, so the task file would be half of that.

tl;dr: if this runs perfectly fine, go ahead with it.

2 Likes