Nodejs File system

I have simple question about fs and async in nodejs.

var fs=require('fs');

fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
    if (err) throw err;
    console.log('Saved!');
  });
  fs.unlink('mynewfile1.txt', function (err) {
    if (err) throw err;
    console.log('File deleted!');
  });

Output I get is this

File deleted!
Saved!

But file is being already deleted and newfile is not created in my dir. Should in’t throw error or create new file. Why neither of this happening?

As pointed out appendFile and unlink are async functions - the real file operations may not follow the order the apis are called

https://nodejs.org/api/fs.html

the unexpected sequence of output lines actually points to a more serious problem

the code as written has a race condition - the outcome is indeterminate - the file may or may not exist after the code runs

a standard fix is to call unlink inside the appendFile callback

node now supports promises and async/await - so either approach below also works

const util=require("util")
// using promises
util.promisify(fs.appendFile)('mynewfile1.txt', 'Hello content!')
.then(()=>{
  console.log('Saved!')
})
.then(()=>util.promisify(fs.unlink)('mynewfile1.txt'))
.then(function() {
  console.log('File deleted!')
})
// catch handler for all errors
.catch(err=>{
  throw err
})
// using async/await
(async ()=>{
  try {
    await util.promisify(fs.appendFile)('mynewfile1.txt', 'Hello content!')
    console.log('Saved!')
    await util.promisify(fs.unlink)('mynewfile1.txt')
    console.log('File deleted!')
  } catch(err) {
    throw err
  }
})()

output is

Saved!
File deleted!
2 Likes