DEV Community

Cover image for Node.js File System – Utilizing unlink() and unlinkSync() for File Deletion
David McCallum
David McCallum

Posted on

Node.js File System – Utilizing unlink() and unlinkSync() for File Deletion

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

 

  1. Import the File System Module: First, you need to import the fs module into your Node.js program.

    import fs from 'fs';
    
  2. Delete File Asynchronously: To delete a file asynchronously, you can use the unlink function. The syntax is as follows:

    fs.unlink(filePath, callbackFunction);
    
  3. Delete File Synchronously: To delete a file synchronously, you can use the unlinkSync function. 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!');
  }
});
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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)