Node Fs - Delete A File Using Unlink or Unlinksync Functions
Node Fs - Delete A File Using Unlink or Unlinksync Functions
To delete a file in Node.js, Node FS unlink(path, callback) can be used for asynchronous file operation and
unlinkSync(path) can be used for synchronous file operation. In this Node.js Tutorial, a step by step guide is
provided to delete a file with node fs and well detailed examples.
Step 2 : Delete file asynchronously using unlink() function. Syntax is provided below
fs.unlink(filePath, callbackFunction)
Once an attempt is made to delete the file, callback function is called with error (as argument) if any.
fs.unlinkSync(filePath)
deleteFile.js
// include node fs
module
var fs = require('fs');
//
// delete
includefile named
node fs module
'sample.txt'
var fs = require('fs');
fs.unlink('sample.txt',
function (err) {
if (err) throw err;
//
// delete file named
if no error, file has'sample.txt'
been deleted
fs.unlink('sample.txt', function (err) {
successfully
console.log('File
if (err) throw err;
deleted!');
}); // if no error, file has been deleted successfully
console.log('File deleted!');
});
$ node deleteFile.js
File deleted!
$ node deleteFile.js
File deleted!
deleteFileSynchronously.js
// include node fs
module
var fs = require('fs');
//
// delete
includefile named
node fs module
'sample.txt'
var fs = require('fs');
Synchronously
fs.unlinkSync('sample.t
xt');
// delete file named 'sample.txt' Synchronously
console.log('File
deleted!');
fs.unlinkSync('sample.txt');
console.log('File deleted!');
Terminal Output
$ node
deleteFileSynchronousl
y.js
File deleted!
$ node deleteFileSynchronously.js
File deleted!
Example: 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.
deleteFile.js
// include node fs
module
// include node fs module
var fs = require('fs');
Terminal Output
$ node deleteFile2.js
/home/arjun/workspace
/nodejs/deleteFile2.js:6
if (err) throw err;
$ node ^deleteFile2.js
/home/arjun/workspace/nodejs/deleteFile2.js:6
Error: ENOENT: no
suchif (err)orthrow
file directory,
err;
unlink 'sample11.txt'
^
As the file is not present, an error is thrown saying ‘no such file or directory’.
Conclusion
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.
Node.js
⊩ Node.js Tutorial
⊩ Node.js - Modules
⊩ Node.js - forEach
Express.js
⊩ Express.js Tutorial
⊩ What is Express.js?
⊩ Install Express.js
⊩ Express.js Routes
⊩ Express.js Middleware
⊩ Express.js Router
Node.js Buffers
Node.js HTTP
Node.js MySQL
⊩ Node.js MySQL
Node.js MongoDB
⊩ Node.js MongoDB
Node.js Mongoose
Node.js URL
⊩ Node FS
Node.js JSON
Node.js Examples
⊩ Node.js Examples
Useful Resources