/

How to Remove a File with Node.js

How to Remove a File with Node.js

In this blog post, we will explore how to remove a file from the file system using Node.js. Node provides two methods to accomplish this: a synchronous method and an asynchronous method through the built-in fs module.

The asynchronous method is fs.unlink(), while the synchronous method is fs.unlinkSync(). The main difference between the two is that the synchronous call will cause your code to block and wait until the file has been removed, while the asynchronous call will not block your code and will execute a callback function once the file deletion is complete.

Let’s see how to use these functions:

fs.unlinkSync()

To remove a file synchronously using fs.unlinkSync(), you can follow this code example:

1
2
3
4
5
6
7
8
9
const fs = require('fs');
const path = './file.txt';

try {
fs.unlinkSync(path);
// File successfully removed
} catch(err) {
console.error(err);
}

In this snippet, we first require the fs module and specify the path of the file we want to delete. Then, within a try block, we call fs.unlinkSync() with the file path. If an error occurs during the deletion process, the catch block will catch and log the error.

To remove a file asynchronously using fs.unlink(), you can use the following code:

1
2
3
4
5
6
7
8
9
10
11
const fs = require('fs');
const path = './file.txt';

fs.unlink(path, (err) => {
if (err) {
console.error(err);
return;
}

// File has been successfully removed
});

In this example, we also require the fs module and specify the file path. Then, we call fs.unlink() with the file path and provide a callback function that handles the error, if any. If an error occurs during the deletion process, it will be logged. Otherwise, the callback function will be executed, indicating that the file has been successfully removed.

By following these examples, you can easily remove files from the file system using Node.js.

Tags: Node.js, file removal, fs module