Node.js Delete File with fs.unlink() and fs.unlinkSync()

To delete a file in Node.js, use the File System module. The asynchronous method is fs.unlink(path, callback), and the synchronous method is fs.unlinkSync(path). In most application code, prefer fs.unlink() or the promise-based fs.promises.unlink() so that file deletion does not block the Node.js event loop.

In this Node.js tutorial, we will delete a file with unlink(), delete a file with unlinkSync(), handle the ENOENT error when the file is missing, and look at a modern async/await example for file deletion.

When to use fs.unlink() and unlinkSync() in Node.js file deletion

Use fs.unlink() when the program can continue running while Node.js performs the delete operation. This is the usual choice for servers, APIs, scripts that process many files, and any code where blocking the event loop is undesirable.

Use fs.unlinkSync() only when a small script must stop and wait until the file is deleted before executing the next statement. Since it is synchronous, it blocks execution until the operation finishes or throws an error.

Node.js methodBehaviorBest use
fs.unlink()Asynchronous callback-based file deleteMost applications and scripts
fs.promises.unlink()Asynchronous promise-based file deleteasync/await code
fs.unlinkSync()Synchronous file deleteSmall scripts where blocking is acceptable

Note: unlink is for deleting files or symbolic links. It is not the right method for deleting directories. For directories, use the appropriate directory removal method such as fs.rm() with suitable options.

Steps to delete a file in Node.js using the fs module

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.

</>
Copy
var fs = require('fs');

We will use unlink() and unlinkSync() functions of this module.

Step 2: Delete file asynchronously using unlink() function. Syntax is provided below

</>
Copy
fs.unlink(filePath, callbackFunction)

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

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

</>
Copy
fs.unlinkSync(filePath)

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

If the file is in the same folder as the script, a relative path such as 'sample.txt' works. For clearer code, especially when the script may be run from another working directory, build an absolute path using path.join(__dirname, fileName).

</>
Copy
const path = require('path');

const filePath = path.join(__dirname, 'sample.txt');

Example 1 – Delete file asynchronously using Node FS unlink() function

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

Create following Node.js program, deleteFile.js, to delete a file named sample.txt in Node.js.

deleteFile.js

</>
Copy
// include node fs module
var fs = require('fs');

// delete file named 'sample.txt'
fs.unlink('sample.txt', function (err) {
	if (err) throw err;
	// if no error, file has been deleted successfully
	console.log('File deleted!');
}); 

Open terminal or command prompt and run this program using node command as shown below.

Output

$ node deleteFile.js
File deleted!

The file is successfully deleted.

Example 2 – 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.

deleteFileSynchronously.js

</>
Copy
// include node fs module
var fs = require('fs');

// delete file named 'sample.txt' Synchronously
fs.unlinkSync('sample.txt');
console.log('File deleted!');

Open terminal or command prompt and run this program using node command as shown below.

Output

$ node deleteFileSynchronously.js
File deleted!

The file is successfully deleted.

Example 3 – 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. We will simulate the condition that we tried to delete a file which is not present at the location.

deleteFile2.js

</>
Copy
// include node fs module
var fs = require('fs');

// delete file named 'sample.txt'
fs.unlink('sample11.txt', function (err) {
	if (err) throw err;
	// if no error, file has been deleted successfully
	console.log('File deleted!');
}); 

Open terminal or command prompt and run this program using node command as shown below.

Output

$ node deleteFile2.js 
/home/arjun/workspace/nodejs/deleteFile2.js:6
	if (err) throw err;
	         ^

Error: ENOENT: no such file or directory, unlink 'sample11.txt'

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

Handle ENOENT safely while deleting a file in Node.js

In production code, throwing every file deletion error may stop the process. If a missing file is acceptable in your program, check err.code and handle ENOENT separately.

deleteIfPresent.js

</>
Copy
const fs = require('fs');

fs.unlink('sample.txt', function (err) {
    if (err) {
        if (err.code === 'ENOENT') {
            console.log('File was already missing.');
            return;
        }

        throw err;
    }

    console.log('File deleted!');
});

In this example, ENOENT means Node.js could not find the file at the given path. Other errors are still thrown because they may indicate permission issues, an invalid path, or another problem that should be fixed.

Delete a file in Node.js using fs.promises.unlink() and async/await

For modern asynchronous code, you can use the promise-based File System API. This keeps the non-blocking behavior and lets you use try...catch for error handling.

deleteFileAsyncAwait.js

</>
Copy
const fs = require('fs/promises');
const path = require('path');

async function deleteFile() {
    const filePath = path.join(__dirname, 'sample.txt');

    try {
        await fs.unlink(filePath);
        console.log('File deleted!');
    } catch (err) {
        if (err.code === 'ENOENT') {
            console.log('File was already missing.');
            return;
        }

        throw err;
    }
}

deleteFile();

Run the script from the terminal using the following command.

</>
Copy
node deleteFileAsyncAwait.js

If the file exists, the program deletes it and prints the following output.

File deleted!

Common Node.js file deletion mistakes with fs.unlink()

  • Using a directory path: fs.unlink() is for files. It fails when the path points to a directory.
  • Ignoring the callback error: Always check the err argument in fs.unlink().
  • Using the wrong working directory: A relative path is resolved from the current working directory, not always from the script file. Use __dirname and path.join() when needed.
  • Blocking a server route with unlinkSync(): In a web server, prefer asynchronous deletion so one request does not block other work.
  • Deleting user-supplied paths without validation: Validate file names and allowed folders before deleting files based on user input.

FAQs on deleting files in Node.js with fs.unlink()

Which is better for deleting a file in Node.js, unlink() or unlinkSync()?

unlink() is usually better because it deletes the file asynchronously and does not block the event loop. Use unlinkSync() only in small scripts where waiting synchronously is acceptable.

How do I delete a file only if it exists in Node.js?

You can call fs.unlink() and handle the ENOENT error. If err.code === 'ENOENT', the file is already missing, so your program can continue safely if that condition is acceptable.

Why do I get ENOENT while deleting a file in Node.js?

ENOENT means Node.js could not find the file at the path you provided. Check the file name, extension, working directory, and whether you need an absolute path using path.join(__dirname, fileName).

Can fs.unlink() delete a folder in Node.js?

No. fs.unlink() is meant for files and symbolic links. To remove a directory, use a directory removal method such as fs.rm() with suitable options for your use case.

How do I delete a file with async/await in Node.js?

Use fs.promises.unlink(), or import unlink from fs/promises, and call it inside an async function with await. Wrap the call in try...catch to handle errors such as ENOENT.

QA checklist for Node.js fs file deletion examples

  • Confirm the tutorial uses fs.unlink() or fs.promises.unlink() for asynchronous deletion examples.
  • Confirm fs.unlinkSync() is described as blocking and suitable only when synchronous behavior is intentional.
  • Confirm every callback example checks the err argument before printing a success message.
  • Confirm the missing-file case explains ENOENT clearly.
  • Confirm file paths are shown safely, especially when relative paths may depend on the current working directory.

Node.js fs file deletion summary

Concluding this Node.js Tutorial – Node FS, we have learned to delete a File in Node.js using Node FS (File System) built-in module. Use fs.unlink() for callback-based asynchronous deletion, fs.promises.unlink() for async/await code, and fs.unlinkSync() only when a synchronous delete operation is specifically required.