Need Help With Node Development?

Work with our skilled Node developers to accelerate your project and boost its performance.

Hire Node.js Developers

Support On Demand!

Using the fs Module to Delete Files

Node.js provides the built-in fs (File System) module to interact with the file system, including deleting files.

Method 1: Using fs.unlink() (Callback-Based)

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

Method 2: Using fs.unlinkSync() (Synchronous)

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

Handling File Not Found Errors

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

Deleting Multiple Files

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

What to Do If You Cannot Delete a File?

  • Ensure you have the correct file path.
  • Check if the file is in use by another process.
  • Ensure you have the necessary permissions to delete the file.

By following these methods, you can effectively remove files in Node.js.

Related Q&A