Node.js provides the built-in fs (File System) module to interact with the file system, including deleting files.
The fs.unlink() method is used to delete a file asynchronously.
Example:
const fs = require('fs');
fs.unlink('path/to/file.txt', (err) => {
if (err) {
console.error('Error deleting file:', err);
} else {
console.log('File deleted successfully');
}
});
The fs.unlinkSync() method deletes a file synchronously.
Example:
const fs = require('fs');
try {
fs.unlinkSync('path/to/file.txt');
console.log('File deleted successfully');
} catch (err) {
console.error('Error deleting file:', err);
}
If the file does not exist, an error will be thrown. It is good practice to check if the file exists before attempting to delete it.
Example:
const fs = require('fs');
const filePath = 'path/to/file.txt';
if (fs.existsSync(filePath)) {
fs.unlink(filePath, (err) => {
if (err) {
console.error('Error deleting file:', err);
} else {
console.log('File deleted successfully');
}
});
} else {
console.log('File does not exist');
}
You can delete multiple files using a loop.
Example:
const fs = require('fs');
const files = ['file1.txt', 'file2.txt', 'file3.txt'];
files.forEach(file => {
fs.unlink(file, (err) => {
if (err) {
console.error(`Error deleting ${file}:`, err);
} else {
console.log(`${file} deleted successfully`);
}
});
});
By following these methods, you can effectively remove files in Node.js.
Work with our skilled Node developers to accelerate your project and boost its performance.
Hire Node.js Developers