Node FS – Delete a File using unlink() or unlinkSync() functions

To delete a file in Node.js, Node FS unlink(path, callback) can be used for asynchronous file operation and unlinkSync(path) can be used for synchronous file operation. In this Node.js Tutorial, a step by step guide is provided to delete a file with node fs and well detailed examples.

Delete a File in Node.js – Node FS unlink()

Following is a step by step guide to delete a File programmatically in Node.js :

  • Step 1 : Include File System module to your Node.js program
     var fs = require(‘fs‘);
  • Step 2 : Delete file asynchronously using unlink() function. Syntax is provided below
     fs.unlink(filePath,callbackFunction)

    Once an attempt is made to delete the file, callback function is called with error (as argument) if any.

    To delete file synchronously, use unlinkSync() function. Syntax is provided below

     fs.unlinkSync(filePath)

    filePath is a String that represents path of the file to be deleted.

 

Example : Delete file asynchronously using Node FS unlink() function

Create following Node.js program to delete a file in Node.js.

For this example, make sure there is a file named ‘sample.txt’ next to the node.js example program.

Run the program using node command in terminal or command prompt :

The file is successfully deleted.

 

Example : Delete file synchronously using Node FS unlinkSync() function

Create following Node.js program to delete a file in Node.js Synchronously. This is helpful if statements next to the delete operation depend on the file you delete. unlinkSync() function makes sure that file is deleted(if it exists) before the execution of subsequent statements.

Run the program using node command in terminal or command prompt :

The file is successfully deleted.

 

Example : Scenario –  File specified to delete is not present. (Error: ENOENT: no such file or directory)

For this example, make sure there is no file named ‘sample11.txt’ next to the node.js example program.

Run the program using node command in terminal or command prompt :

As the file is not present, an error is thrown saying ‘no such file or directory’

 

Conclusion :

In this Node.js TutorialNode FS, we have learnt to delete a File in Node.js using Node FS (File System) built-in module.