Deleting file in Node.js

Viewed 19808

I am using node in a Windows environment. When I use fs.unlinkSync(fileName), it seems to work. After the unlinkSync statement is executed, if I do a fs.existsSync(filename) it returns false indicating the file does not exists, but when I go to the physical drive I can still see the file.

At this point in time if I try and delete the file manually, it throws Access denied. However, the file is automatically removed from the file system only when I stop the executing node script file.

Is this the expected behavior?

2 Answers

I had similar problem when I was using this to create a new file

lib.create = function (directory, fileName, data) {
  return fs.promises.open(`${lib.baseDir}${directory}/${fileName}.json`, "wx")
    .then(fileHandle => {
      // Convert data to string
      const stringData = JSON.stringify(data);

      return fileHandle.writeFile(stringData)
        .then(() => Promise.resolve(`File '${fileName}.json' saved successfully`))
        .catch(() => Promise.reject("Error writing to new file"));
    })
    .catch(() => Promise.reject("Could not create new file, it may already exist"));
}; 

and this to delete file

lib.delete = function (directory, fileName) {
  return fs.promises.unlink(`${lib.baseDir}${directory}/${fileName}.json`)
    .then(() => Promise.resolve(`File '${fileName}.json' deleted successfully`))
    .catch(() => Promise.reject(`Error deleting a ${fileName}.json`))
};

my file was deleted after killing node app. The reason is that

fileHandle.writeFile

dosen't close the file automatically and what needs to be done is

fileHandle.writeFile

returns a Promise so we can add another then and there close the file

return fileHandle.writeFile(stringData)
   .then(() => fileHandle.close())
      .then(() => Promise.resolve(`File '${fileName}.json' saved successfully`))
   .catch(() => Promise.reject("Error writing to new file"));

now my delete works good!

Related