Search code examples
node.jsasynchronouswritefile

Sync vs async for file write in NodeJS


I've recently been told sync functions completly block the app while they are in use. That is why I want to convert the functionality of the code below to async. I recive an optimized image, save the file as a .webp format and delete the old nonoptimized one. Than the new user_file gets saved to a database right after this.

fs.writeFileSync(req.file.path + '.webp', data);
user_file = user_file + '.webp';
fs.unlinkSync(req.file.path);

If I just convert it to async like this it just goes on and inserts the old user_file:

fs.writeFile(req.file.path + '.webp', data, err => {
  if (err) {
    console.error(err);
    return;
  }
  fs.unlink(req.file.path, (err) => {
    if (err) {
      console.error(err);
      return;
    }
    user_file = user_file + '.webp';
  });
});  // I could just put user_file = user_file + '.webp'; here but I also want to make sure that it was successfully saved before moving on

How do I keep this async but still wait for the functions to be fully completed before moving on to db insertions?


Solution

  • Use fs.Promises API instead of a classic with a callback.

    await fsPromises.writeFile(req.file.path + '.webp', data)