In Node.js, you can delete files using the built-in fs (File System) module. The fs module provides both asynchronous and synchronous methods to delete files: unlink for asynchronous operations and unlinkSync for synchronous operations.
Steps to Delete a File in Node.js
-
Import the File System Module: First, you need to import the
fsmodule into your Node.js program.
import fs from 'fs'; -
Delete File Asynchronously: To delete a file asynchronously, you can use the
unlinkfunction. The syntax is as follows:
fs.unlink(filePath, callbackFunction); -
Delete File Synchronously: To delete a file synchronously, you can use the
unlinkSyncfunction. The syntax is:
fs.unlinkSync(filePath);
Example 1: Delete File Asynchronously with Error Handling
In this example, make sure you have a file named exampleFile.txt in the same directory as your Node.js program. The following Node.js program deletes the file and includes error handling:
import fs from 'fs';
// Delete file named 'exampleFile.txt'
fs.unlink('exampleFile.txt', (err) => {
if (err) {
console.error('An error occurred:', err);
} else {
console.log('File deleted successfully!');
}
});
Run the program using the node command. Depending on whether the file is successfully deleted or an error occurs, the appropriate message will be displayed.
Example 2: Delete File Synchronously with Error Handling
This example demonstrates synchronous file deletion with error handling. This is useful when subsequent statements depend on the deletion of the file.
import fs from 'fs';
try {
// Delete file named 'exampleFile.txt' synchronously
fs.unlinkSync('exampleFile.txt');
console.log('File deleted successfully!');
} catch (err) {
console.error('An error occurred:', err);
}
Run the program using the node command. If the file is deleted successfully, you'll see the message "File deleted successfully!". If an error occurs, the error message will be displayed.
Top comments (0)