EN
Node.js - delete files
0
points
In this article, we would like to show you how to delete files in Node.js.
Below we will present 3 methods to delete files in node.js:
- synchronously,
- asynchronously with callback,
- asynchronously with async/await.
Synchronously
const fs = require('fs');
try {
fs.unlinkSync('./fileToDelete.txt');
console.log('successfully deleted fileToDelete.txt');
} catch (error) {
console.log(error);
}
Asynchronously with callback
const fs = require('fs');
fs.unlink('./fileToDelete.txt', (error) => {
if (error) {
console.error(error.message);
} else {
console.log('successfully deleted');
}
});
Asynchronously with async/await
const fs = require('fs/promises');
const deleteFile = async (path) => {
try {
await fs.unlink(path);
console.log('successfully deleted');
} catch (error) {
console.error(error.message);
}
};
deleteFile('./fileToDelete.txt');