| by Arround The Web | No comments

How to Remove Files in Node.js Using “fs.unlink”?

The file system “fs” module provides various methods by which the basic operations like read, file, delete, append, and other related operations can be performed easily. However, the operation of deletion is mostly performed on a daily basis by the developers. This deletion operation can be directly performed using the GUI interface or by the utilization of the “fs” module method named “unlink()”.

This guide explains the procedure to remove files in Node.js with the help of “fs.unlink()” by explaining the below sections:

How to Remove a File Using the “fs.unlink()” Method

The “fs.unlink()” is a synchronous or blocking method as it stops the execution of all other processes until the specified file gets deleted completely. This “fs.unlink()” method can also be utilized to remove the assigned “symbolic” links that point to the targeted file system.

Syntax

The “fs.unlink()” method syntax is shown below:

fsObj.unlink( filePath, callbackFunc )

In the above syntax:

  • The “fsObj” is the variable that is acting as the object of a “fs” module.
  • The “filePath” is the path of the file residing inside the project directory which needs to be deleted.
  • The “callbackFunc” is the required arrow function that helps in displaying the result messages or errors that have arisen during processing.

Let’s walk through a couple of examples for practical implementation of the “fs.unlink()” method.

Example 1: Use of “fs.unlink()” Method to Remove a File

In this example, a random project file is going to be deleted or removed from a file from the project directory using the “fs.unlink()” method. Its practical implementation is shown in the below code block:

var deleteFile = require('fs');

deleteFile.unlink('linuxhintFile.txt', function (error) {

  if (error) throw error;

  console.log('The Operation for File Deletion is Performed Successfully!');

});

console.log('Deletion Operation is Ended!');

In the above code block:

  • First, the “fs” module has been imported and its object is stored in a new variable named “deleteFile”.
  • Then, the “unlink()” method is called using the variable, and the file name that needs to be deleted is passed as the first parameter.
  • Its second callback function is also utilized to catch and display any occurred error during the completion of operation.
  • In case of no error, display a success message. To confirm the asynchronous behavior of this method, write a code that displays a dummy message outside the “unlink()” method scope.

Store the above code in a desired file having an extension of “.js” which is “proApp.js” in our case and run the below command to perform execution:

node proApp.js

The generated output shows that the selected file has been deleted from the project directory. Also, the asynchronous behavior of this method is confirmed because the message written after the method is executed first:

Example 2: Use of “fs.unlink()” Method to Remove a Symbolic Link

The “symbolic” links have no physical existence in the file but they contain the relative or absolute path as a reference for other attached files. Its usage can increase the performance of the application while consuming less space. This symbolic link is created with the help of the “fs.symlinkSync()” or “fs.symlinkSync()” methods and for deletion the “fs.unlink()” is used, as shown below:

const fsObj = require('fs');

// Establishing the symbolic link
fsObj.symlinkSync(__dirname + "\\index.html", "symbolicFile");
console.log("\nEstablished Symbolic link to index.html File");

retrieveFiles();

 fsObj.unlink("symbolicFile", (error => {
if (error) console.log(error);
else {
    console.log("\nDeleted Established Link: symbolicFile");
    // Get the files in current directory after deletion
    retrieveFiles();
   }
}
));

// Function to get current filenames in a directory with specific extension
function retrieveFiles() {
 console.log("\nAvailable Files in the Current Project:");
 let assets = fsObj.readdirSync(__dirname);
 assets.forEach(asset => {
    console.log(asset);
 });
}

The explanation of the above code block is as follows:

  • Import the “fs” module and store its object in the “fsObj” named variable.
  • Create a symbolic link to the current project file named “index.html” and assign the name “symbolicFile” to the created symbolic link file. The “__dirname” property is used to retrieve the absolute path for the current project directory.
  • With the help of the “console.log()” method displays a success message and invokes the custom-defined “retrieveFiles()” function.
  • Now, invoke the “unlink()” method via “fsObj” and pass the symbolic file name as the first parameter that needs to be deleted. This method requires a callback function that is used to catch and display any arisen errors.
  • Display a deletion message and again invoke the “retrieveFiles()” function if there are no errors.
  • After that, define a “retrieveFiles()” function that reads the current project directories using the “readdirSync()” function. Finally, all residing directories are displayed over the console using the enhanced “forEach” loop.

Now, run the above code by executing the containing “.js” type file. The containing file in our case is “proApp.js” so, our command to execute will be:

node proApp.js

The generated output shows that the symbolic link has been established and then deleted via the “fs.unlink()” method:

Bonus Tip: What is the “fs.unlinkSync()” Method?

The “unlinkSync()” method is also provided by the “fs” module; it is the “synchronous” version of the “unlink()” method. The “unlinkSync()” method can be used to perform the same operations of deleting a file or symbolic files but in a Synchronous way. It blocks all overcoming processes until the targeted file doesn’t get deleted, as shown below:

var deleteFile = require('fs');

deleteFile.unlinkSync('linuxhintFile.txt');

console.log('Deletion Operation is Ended!');

In the above code block:

  • First, the “fs” module has been imported and its object is stored in a new variable named “deleteFile”.
  • Then, the “unlinkSync()” method is called using the “deleteFile” variable, and the file name that needs to be deleted is passed as its parameter.
  • To confirm the “synchronous” behavior of this method, write a code that displays a dummy message next to the “unlinkSync()” method.

Store the above code in a desired file having an extension of “.js” which is “proApp.js” in our case and run the below command to perform execution:

That’s all about the removal of files in Node.js using the “fs.unlink()” method.

Conclusion

To remove files in Node.js, pass the targeted file path as the first and the callback function to handle errors and to perform other stuff as the second parameter for the “unlink()” method. The “unlink()” method is used to delete the symbolic linked files as well. This method has the synchronous version as well named as “unlinkSync()” method which acts similarly to “unlink()” method, but it does not include the “callback” function part. This guide has explained the process of removing the files via the “fs.unlink()” method.

Share Button

Source: linuxhint.com

Leave a Reply