Node js - Deleting Files and Directories

Node.js - Deleting Files and Directories

Deleting Files and Directories in Node.js

Introduction

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.

Understanding the fs Module

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:

  • Callback-based (legacy style)
  • Promise-based via fs/promises
const fs = require('fs');
const fsp = require('fs/promises');

Deleting Files in Node.js

Using fs.unlink (Asynchronous)

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');
});

Using fs.unlinkSync (Synchronous)

const fs = require('fs');

try {
    fs.unlinkSync('delete-me.txt');
    console.log('File deleted synchronously');
} catch (err) {
    console.error('Failed to delete file:', err);
}

Using fs.promises.unlink (Promise-based)

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');

Error Handling Tips

  • Check if file exists before trying to delete it
  • Always wrap deletions in try/catch for reliability

Checking File Existence Before Deletion

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');
}

Deleting Multiple Files

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`);
        }
    });
});

Deleting Files with Extension Filters

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`);
            });
        }
    });
});

Deleting Directories in Node.js

Using fs.rmdir (Deprecated)

Note: fs.rmdir() was used to delete directories but has been deprecated in favor of fs.rm().

Using fs.rm (Recommended in Node 14.14+)

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');
    }
});

Using fs.promises.rm

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');

Deleting Empty Directory Using fs.rmdirSync

const fs = require('fs');

try {
    fs.rmdirSync('empty-dir');
    console.log('Empty directory deleted');
} catch (err) {
    console.error('Error:', err.message);
}

Recursively Deleting Files and Subdirectories

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');

Watching Files Before Deletion

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');
        });
    }
});

Using path.join() for Safe Deletion

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');
});

Using Glob to Delete Multiple Files

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`);
        });
    });
});

Handling Permissions

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'));
});

Best Practices

  • Use fs.promises with async/await for clean code
  • Validate file/directory existence before deletion
  • Log all deletions for audit or rollback
  • Never hardcode paths; use path.join
  • Avoid recursive deletes without confirmation in critical systems

Real-World Use Cases

Temporary File Cleanup

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`);
        });
    });
}

User Upload Management

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.

Beginner 5 Hours
Node.js - Deleting Files and Directories

Deleting Files and Directories in Node.js

Introduction

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.

Understanding the fs Module

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:

  • Callback-based (legacy style)
  • Promise-based via fs/promises
const fs = require('fs'); const fsp = require('fs/promises');

Deleting Files in Node.js

Using fs.unlink (Asynchronous)

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'); });

Using fs.unlinkSync (Synchronous)

const fs = require('fs'); try { fs.unlinkSync('delete-me.txt'); console.log('File deleted synchronously'); } catch (err) { console.error('Failed to delete file:', err); }

Using fs.promises.unlink (Promise-based)

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');

Error Handling Tips

  • Check if file exists before trying to delete it
  • Always wrap deletions in try/catch for reliability

Checking File Existence Before Deletion

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'); }

Deleting Multiple Files

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`); } }); });

Deleting Files with Extension Filters

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`); }); } }); });

Deleting Directories in Node.js

Using fs.rmdir (Deprecated)

Note: fs.rmdir() was used to delete directories but has been deprecated in favor of fs.rm().

Using fs.rm (Recommended in Node 14.14+)

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'); } });

Using fs.promises.rm

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');

Deleting Empty Directory Using fs.rmdirSync

const fs = require('fs'); try { fs.rmdirSync('empty-dir'); console.log('Empty directory deleted'); } catch (err) { console.error('Error:', err.message); }

Recursively Deleting Files and Subdirectories

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');

Watching Files Before Deletion

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'); }); } });

Using path.join() for Safe Deletion

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'); });

Using Glob to Delete Multiple Files

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`); }); }); });

Handling Permissions

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')); });

Best Practices

  • Use fs.promises with async/await for clean code
  • Validate file/directory existence before deletion
  • Log all deletions for audit or rollback
  • Never hardcode paths; use path.join
  • Avoid recursive deletes without confirmation in critical systems

Real-World Use Cases

Temporary File Cleanup

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`); }); }); }

User Upload Management

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.

Related Tutorials

Frequently Asked Questions for Node.js

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.

line

Copyrights © 2024 letsupdateskills All rights reserved