Delete a file in Node using unlink() and unlinkSync() method
Short tutorial on how to remove a file from the file system in node js using unlink() and unlinkSync() functions.
In this short post, we will learn how to delete/remove a file from the filesystem in Node JS.
In Node, you can delete a file using the unlink() and unlinkSync() method that is provided by the fs module. This function helps to delete a file from the local filesystem using Node Js.
Let's see how both functions work using an example.
Remove a file asynchronously in Node using unlink() method.
The fs.unlink() method is an asynchronous method that does not block the execution of the node event loop while removing the file from the local filesystem.
The syntax of deleting a file using fs.unlink() is:
fs.unlink(filePath, callbackFunction)
Once the file is deleted the callback function is executed to check for errors during the removal of the file.
Example:
const fs = require('fs') const filePath = './myfile.txt' fs.unlink(filePath, (err) => { if (err) { console.error(err) return'; } //file deleted })
You have to include the fs mode first and then use pass the path of the file and the callback function as an argument.
If there is any error in deleting the file it will show the error in the console and return the function.
Delete file synchronously using unlinkSync() method in Node
We can also delete a file synchronously from the local filesystem using fs.unlinkSync() function in Node. This method will block the execution of the node even loop until the file is removed.
The syntax of unlinkSync() method is
fs.unlinkSync(filePath)
Now let's see an example to delete a file.
const fs = require('fs') const filePath = './myfile.txt' try { fs.unlinkSync(filePath) //file deleted from the system } catch(err) { console.error(err) }
Here, we have used the fs.unlinkSync() method inside a try..catch statement. If there is an error during the removal of the file then we can catch the error and display it in the console.
Related Posts
Press Shift + Enter for new Line in Textarea
Override default textarea behavior on Enter key press without Shift, prevent new lines, and take custom actions like submitting forms instead. Still allow Shift+Enter newlines.
in vs hasOwnProperty(): Differences in Inherited Properties
The article explains the differences between JavaScript's 'in' operator and 'hasOwnProperty()' method. And also learn the use cases of both in JS.
How to Fix "ReferenceError: document is not defined" in JavaScript
The "ReferenceError: document is not defined" is a common error in JavaScript that occurs when trying to access the `document` object in a non-browser environment like Node.js.
How to Fix the "Cannot Read Property of Undefined" Error in JavaScript
The "Cannot read property of undefined" error occurs when you try to access a property or method of a variable that is undefined in JavaScript.
