Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
How do you remove a file from the filesystem using Node.js?
Node offers a synchronous method, and an asynchronous method through the fs built-in module.
The asynchronous one is fs.unlink().
The synchronous one is fs.unlinkSync().
The difference is simple: the synchronous call will cause your code to block and wait until the file has been removed. The asynchronous one will not block your code, and will call a callback function once the file has been deleted.
Here is how to use both:
fs.unlinkSync():
const fs = require('fs')
const path = './file.txt'
try {
fs.unlinkSync(path)
// file removed
} catch (err) {
console.error(err)
}
fs.unlink():
const fs = require('fs')
const path = './file.txt'
fs.unlink(path, (err) => {
if (err) {
console.error(err)
return
}
// file removed
})