How to remove a file with Node.js

By

Learn how to remove a file from the filesystem in Node.js with the fs module, using the asynchronous fs.unlink() or the blocking fs.unlinkSync() method.

~~~

To remove a file from the filesystem in Node.js, use the fs built-in module. It gives you fs.unlink(), which is asynchronous, and fs.unlinkSync(), which is synchronous.

The name comes from the underlying operating system call, unlink. Deleting a file on Unix means removing its link from the directory. Node kept the same name.

The difference between the two is when your code gets control back. The synchronous call blocks and waits until the file has been removed. The asynchronous one does not block, and calls a callback function once the file has been deleted.

The synchronous version

fs.unlinkSync() removes the file right there. Wrap it in a try/catch, because it throws if anything goes wrong:

const fs = require('fs')

const path = './file.txt'

try {
  fs.unlinkSync(path)
  //file removed
} catch (err) {
  console.error(err)
}

This is fine in scripts and command line tools, where blocking for a moment doesn’t hurt anyone.

The asynchronous version

fs.unlink() takes the path and a callback. The callback receives an error, or null on success:

const fs = require('fs')

const path = './file.txt'

fs.unlink(path, (err) => {
  if (err) {
    console.error(err)
    return
  }

  //file removed
})

Use this one in servers, where blocking the event loop means every other request waits too.

The promise version

If you’re using async/await, the same method exists in the promise-based API of the module:

const fs = require('fs/promises')

await fs.unlink('./file.txt')

Same behavior as the callback version, without the callback.

What errors to expect

The most common one is trying to remove a file that doesn’t exist. You get an error with the code ENOENT:

fs.unlink('./missing.txt', (err) => {
  if (err) {
    console.error(err.code) //ENOENT
  }
})

If deleting an already-gone file is fine for your program, check for that code and ignore it.

One pitfall to be aware of: fs.unlink() only works on files. Point it at a directory and you get an error (the exact code depends on the operating system). To remove a directory, use fs.rmdir(), or fs.rm() with the recursive option if the directory has content in it.

Tagged: Node.js · All topics
~~~

Related posts about node: