Deleting Files in Node.js
Deleting files is an important file-handling operation in Node.js. The File System module provides methods to remove files from the file system using JavaScript code.
For example, an application may need to remove temporary files,
outdated reports, or unnecessary text files. Node.js provides
fs.unlink() and fs.unlinkSync() to delete
files.
1. What Does Deleting a File Mean?
Deleting a file means removing a file from its location in the file system. Once a file has been deleted successfully, it cannot normally be accessed through its previous path.
Suppose an application creates a temporary file named
temp.txt. After completing its work, the
application may delete that file because it is no longer needed.
temp.txt
fs.unlink()
temp.txt no longer exists at that path
2. The fs.unlink() Method
The fs.unlink() method deletes a file
asynchronously. It allows other JavaScript work to continue
while the file operation is being handled.
Syntax:
fs.unlink(path, callback);
Parameters:
| Parameter | Meaning |
|---|---|
path |
The path of the file to delete. |
callback |
A function called when the deletion operation completes or fails. |
The callback follows the error-first pattern:
(err). If deletion succeeds, the error is
null. If the operation fails, the error parameter
contains information about the failure.
fs.unlink() is used
to delete files, not to remove directories. We will learn
directory operations in the next lesson.
3. First Example: Delete a Text File
Let's create a file named temp.txt and delete it
using Node.js.
Step 1: Create a Project Folder
mkdir DeletingFilesDemo
cd DeletingFilesDemo
npm init -y
Step 2: Create temp.txt
Create a file named temp.txt in the project folder
and add the following content.
This is a temporary file.
It is no longer required.
Step 3: Create app.js
const fs = require("fs");
fs.unlink("temp.txt", (err) => {
if (err) {
console.log("Error deleting file:", err.message);
return;
}
console.log("File deleted successfully!");
});
Step 4: Run the Program
node app.js
Output:
File deleted successfully!
After successful execution, temp.txt is removed
from the project folder.
Before execution:
app.js
temp.txt
After successful deletion:
app.js
Explanation:
require("fs")imports the File System module."temp.txt"specifies the file to delete.fs.unlink()starts the asynchronous deletion operation.if (err)checks whether the operation failed.- The success message is displayed only after successful deletion.
4. Handling Errors While Deleting Files
File deletion can fail if the file does not exist, the path is incorrect, or the application does not have sufficient permissions.
Therefore, we should always check the error parameter before displaying a success message.
Example: Delete a Missing File
const fs = require("fs");
fs.unlink("unknown.txt", (err) => {
if (err) {
console.log("Unable to delete file.");
console.log(err.message);
return;
}
console.log("File deleted successfully!");
});
If unknown.txt does not exist, the deletion
operation fails.
Example output:
Unable to delete file.
ENOENT: no such file or directory ...
The complete error message depends on the operating system and the file path.
return statement
prevents the callback from continuing to the success message
after an error.
5. The fs.unlinkSync() Method
The fs.unlinkSync() method deletes a file
synchronously. The program waits for the deletion operation
to complete before continuing.
Syntax:
fs.unlinkSync(path);
Example
First, make sure that a file named oldFile.txt
exists in the current project directory.
const fs = require("fs");
try {
fs.unlinkSync("oldFile.txt");
console.log("File deleted successfully!");
} catch (err) {
console.log("Error deleting file:", err.message);
}
Output when the file exists:
File deleted successfully!
If the file does not exist, the method throws an exception.
The catch block handles that exception and
displays an error message.
| Feature | fs.unlink() | fs.unlinkSync() |
|---|---|---|
| Operation | Asynchronous | Synchronous |
| Completion | Handled through a callback | Returns after deletion completes |
| Error handling | Check the callback error | Use try...catch |
| Blocking | Does not block while waiting for the deletion operation | Blocks further JavaScript execution until it finishes |
Asynchronous methods are generally preferred for regular file operations in server applications when blocking execution is undesirable.
6. Delete a File After Checking Whether It Exists
Sometimes, an application needs to check whether a file exists
before deleting it. One option is to use
fs.access() before calling fs.unlink().
const fs = require("fs");
fs.access("temp.txt", fs.constants.F_OK, (accessErr) => {
if (accessErr) {
console.log("File does not exist.");
return;
}
fs.unlink("temp.txt", (deleteErr) => {
if (deleteErr) {
console.log("Error deleting file:", deleteErr.message);
return;
}
console.log("File deleted successfully!");
});
});
Possible output when the file exists:
File deleted successfully!
Possible output when the file is missing:
File does not exist.
The example checks the file first and then attempts deletion.
However, the file could change between these two operations.
For many applications, calling fs.unlink()
directly and handling its error is simpler and more reliable.
7. Delete Multiple Files
If an application needs to delete several files, we can use
fs.unlink() for each file and wait for all
operations to finish.
In this example, make sure all three files exist in the project directory before running the program.
const fs = require("fs");
const { promisify } = require("util");
const unlinkAsync = promisify(fs.unlink);
async function deleteFiles() {
const files = [
"temp1.txt",
"temp2.txt",
"temp3.txt"
];
for (const file of files) {
try {
await unlinkAsync(file);
console.log(`${file} deleted successfully.`);
} catch (err) {
console.log(`Could not delete ${file}: ${err.message}`);
}
}
}
deleteFiles();
Example output when all files exist:
temp1.txt deleted successfully.
temp2.txt deleted successfully.
temp3.txt deleted successfully.
The loop processes the files one at a time. If a file cannot be deleted, its error is displayed and the loop continues with the next file.
8. Difference Between Deleting Files and Directories
Files and directories are different types of file-system resources. The method used to delete a file is not the same as every method used to remove a directory.
| Operation | Method | Purpose |
|---|---|---|
| Delete a file | fs.unlink() |
Removes a file. |
| Delete a file synchronously | fs.unlinkSync() |
Removes a file synchronously. |
| Create a directory | fs.mkdir() |
Creates a directory. |
| Read directory contents | fs.readdir() |
Lists directory entries. |
| Remove a directory | fs.rmdir() or fs.rm(), as appropriate |
Removes a directory, subject to the method's rules and options. |
We will explore directory operations in the next lesson.
9. Common Mistakes While Deleting Files
| Mistake | Solution |
|---|---|
| Using the wrong file name | Verify the file name and extension. |
| Using an incorrect path | Check the path relative to the current working directory. |
| Not handling deletion errors | Check the callback error or use try...catch. |
| Using unlink() to remove a directory | Use the appropriate directory-removal method. |
| Displaying success before deletion completes | Display the success message inside the callback after successful deletion. |
| Deleting important files accidentally | Verify the path and confirm the file is safe to delete. |
10. Practice Tasks
Task 1: Delete a Temporary File
- Create a project folder named
TempFileApp. - Initialize the project using
npm init -y. - Create a file named
temp.txt. - Write a Node.js program using
fs.unlink(). - Handle errors if the file does not exist.
- Display a success message after deletion.
Expected result: The file should be removed successfully, and a confirmation message should appear in the terminal.
Task 2: Delete Old Report Files
- Create three test files named
report1.txt,report2.txt, andreport3.txt. - Create an array containing these file names.
- Delete each file using an asynchronous method.
- Handle each file's error separately.
- Display a message for every successful deletion.
Expected result: Each existing test file should be deleted, and the terminal should show the corresponding result.
Summary
Deleting files in Node.js allows applications to remove
unnecessary files from the file system. The
fs.unlink() method deletes a file
asynchronously, while fs.unlinkSync()
deletes it synchronously. Both methods can fail when a
file does not exist or the application lacks the required
permissions.
In this lesson, we learned how to delete one file, handle errors, check file existence, and process multiple files. We also understood the difference between deleting files and removing directories. These techniques help developers manage temporary files and other application resources safely in Node.js projects at CIIT Training Institute.