In any application that interacts with the file system, itβs common to manage files and directories dynamically β including deletion. Whether it's a user removing a profile photo, a script clearing log files, or an automation process managing temp data, deleting files and directories is essential. Node.js provides both synchronous and asynchronous methods to delete files and folders via its built-in fs and fs/promises modules.
This guide will walk through different ways to delete files and directories in Node.js, including using callbacks, promises, synchronous methods, recursive deletions, and error handling. We will also discuss best practices and safety checks to ensure clean, efficient, and reliable file deletion in your applications.
The fs module is a built-in Node.js module that provides file system-related functionalities such as reading, writing, renaming, and deleting files and directories. You can use it in two forms:
const fs = require('fs');
const fsp = require('fs/promises');
fs.unlink() is the standard asynchronous method used to delete a single file.
const fs = require('fs');
fs.unlink('delete-me.txt', (err) => {
if (err) {
console.error('Error deleting file:', err);
return;
}
console.log('File deleted successfully');
});
const fs = require('fs');
try {
fs.unlinkSync('delete-me.txt');
console.log('File deleted synchronously');
} catch (err) {
console.error('Failed to delete file:', err);
}
const fsp = require('fs/promises');
async function deleteFile(filePath) {
try {
await fsp.unlink(filePath);
console.log('File deleted with promises');
} catch (err) {
console.error('Error:', err.message);
}
}
deleteFile('delete-me.txt');
const fs = require('fs');
if (fs.existsSync('delete-me.txt')) {
fs.unlink('delete-me.txt', (err) => {
if (err) throw err;
console.log('File deleted');
});
} else {
console.log('File does not exist');
}
const fs = require('fs');
const files = ['file1.txt', 'file2.txt', 'file3.txt'];
files.forEach(file => {
fs.unlink(file, (err) => {
if (err) {
console.error(`Failed to delete ${file}`);
} else {
console.log(`${file} deleted`);
}
});
});
To delete only specific file types like .log or .tmp:
const fs = require('fs');
const path = require('path');
fs.readdir('./logs', (err, files) => {
if (err) throw err;
files.forEach(file => {
if (path.extname(file) === '.log') {
fs.unlink(`./logs/${file}`, err => {
if (err) console.error(err);
else console.log(`${file} deleted`);
});
}
});
});
Note: fs.rmdir() was used to delete directories but has been deprecated in favor of fs.rm().
To delete a directory:
const fs = require('fs');
fs.rm('my-folder', { recursive: true, force: true }, (err) => {
if (err) {
console.error('Failed to delete directory:', err);
} else {
console.log('Directory deleted');
}
});
const fsp = require('fs/promises');
async function deleteDir(dirPath) {
try {
await fsp.rm(dirPath, { recursive: true, force: true });
console.log('Directory deleted with fs.promises');
} catch (err) {
console.error(err);
}
}
deleteDir('my-folder');
const fs = require('fs');
try {
fs.rmdirSync('empty-dir');
console.log('Empty directory deleted');
} catch (err) {
console.error('Error:', err.message);
}
If you're using older Node.js versions, you can build a recursive function.
const fs = require('fs');
const path = require('path');
function deleteRecursive(dirPath) {
if (fs.existsSync(dirPath)) {
fs.readdirSync(dirPath).forEach(file => {
const curPath = path.join(dirPath, file);
if (fs.lstatSync(curPath).isDirectory()) {
deleteRecursive(curPath);
} else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(dirPath);
}
}
deleteRecursive('folder-to-delete');
const fs = require('fs');
fs.watch('delete-me.txt', (eventType) => {
if (eventType === 'change') {
console.log('File changed. Ready to delete...');
fs.unlink('delete-me.txt', (err) => {
if (err) throw err;
console.log('Deleted after modification');
});
}
});
const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, 'uploads', 'image.jpg');
fs.unlink(filePath, (err) => {
if (err) throw err;
console.log('Image deleted');
});
For complex patterns, install glob module:
const fs = require('fs');
const glob = require('glob');
glob('*.log', (err, files) => {
files.forEach(file => {
fs.unlink(file, err => {
if (err) console.error(err);
else console.log(`${file} deleted`);
});
});
});
const fs = require('fs');
fs.chmod('file.txt', 0o666, (err) => {
if (err) console.error('Permission change failed');
else fs.unlink('file.txt', () => console.log('Deleted with new permissions'));
});
const fs = require('fs');
function clearTempFiles() {
const tempFiles = ['temp1.tmp', 'temp2.tmp'];
tempFiles.forEach(file => {
fs.unlink(file, err => {
if (!err) console.log(`${file} removed`);
});
});
}
const fs = require('fs');
function deleteUserUpload(fileName) {
fs.unlink(`uploads/${fileName}`, err => {
if (err) console.error('Failed to delete user file');
else console.log('User file deleted');
});
}
Deleting files and directories in Node.js is straightforward thanks to the powerful and flexible fs module. With support for asynchronous, synchronous, and promise-based deletion, you have the tools needed to manage files efficiently. Whether you're removing temporary files, managing user uploads, or cleaning logs, it's important to ensure proper error handling, path validation, and usage of modern APIs like fs.promises.
As Node.js evolves, newer methods like fs.rm() offer more reliable and consistent behavior. Always prefer asynchronous or promise-based approaches to maintain performance in production systems. With good practices, robust error handling, and a clear understanding of the underlying APIs, you can safely manage file and directory deletion in your Node.js applications.
A function passed as an argument and executed later.
Runs multiple instances to utilize multi-core systems.
Reusable blocks of code, exported and imported using require() or import.
nextTick() executes before setImmediate() in the event loop.
Starts a server and listens on specified port.
Node Package Manager β installs, manages, and shares JavaScript packages.
A minimal and flexible web application framework for Node.js.
A stream handles reading or writing data continuously.
It processes asynchronous callbacks and non-blocking I/O operations efficiently.
Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.
An object representing the eventual completion or failure of an asynchronous operation.
require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).
Use module.exports or exports.functionName.
Variables stored outside the code for configuration, accessed using process.env.
MongoDB, often used with Mongoose for schema management.
Describes project details and manages dependencies and scripts.
Synchronous blocks execution; asynchronous runs in background without blocking.
Allows or restricts resources shared between different origins.
Use try-catch, error events, or middleware for error handling.
Provides file system-related operations like read, write, delete.
Using event-driven architecture and non-blocking I/O.
Functions in Express that execute during request-response cycle.
A set of routes or endpoints to interact with server logic or databases.
Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.
Middleware to parse incoming request bodies, like JSON or form data.
Copyrights © 2024 letsupdateskills All rights reserved