Node.js FS Delete File

To delete a file using JavaScript, you can use the fs module in the Node.js environment. This module provides a way to work with the file system, including creating, reading, writing, and deleting files.

To delete a file, you can use the fs.unlink() method, which takes the path to the file as an argument and returns a Promise that is resolved when the file has been successfully deleted.

Here is an example of how to use the fs.unlink() method to delete a file:

const fs = require('fs'); const filePath = 'path/to/file.txt'; fs.unlink(filePath) .then(() => { console.log(`${filePath} was deleted successfully`); }) .catch((err) => { console.error(`Error deleting ${filePath}:`, err); });
Code language: JavaScript (javascript)

In this example, the fs.unlink() method is called with the path to the file that should be deleted. If the file is deleted successfully, a message is logged to the console. If there is an error, it is caught and logged to the console.

Another Option: fs.unlinkSync()

Another method that can be used to delete a file in Node.js is the fs.unlinkSync() method.

This method is similar to the fs.unlink() method, but it is a synchronous version that does not return a Promise. Instead, it immediately performs the delete operation and returns a value indicating whether the operation was successful or not.

Here is an example of how to use the fs.unlinkSync() method to delete a file:

const fs = require('fs'); const filePath = 'path/to/file.txt'; try { fs.unlinkSync(filePath); console.log(`${filePath} was deleted successfully`); } catch (err) { console.error(`Error deleting ${filePath}:`, err); }
Code language: JavaScript (javascript)

In this example, the fs.unlinkSync() method is called with the path to the file that should be deleted.

If the file is deleted successfully, a message is logged to the console. If there is an error, it is caught and logged to the console.

One important difference between the fs.unlink() and fs.unlinkSync() methods is that the synchronous version will block the execution of the program until the delete operation is completed.

This can make your program less responsive and may cause performance issues if the delete operation takes a long time to complete.

Therefore, it is generally recommended to use the asynchronous version (fs.unlink()) unless you have a specific reason for needing a synchronous operation.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *