How To Delete File Using Node.js

By Yashwant Chavan, Views 132908, Last updated on 02-Mar-2019

In this tutorial, You will learn how to delete a file using node.js, This post will cover file deletion in synchronous and asynchronous manner.

tags nodejs

syntax

fs.unlink(path, callback)

delete file asynchronous manner. No arguments other than a possible exception are given to the completion callback.

path - <String> or <Buffer>

callback - <Function>

fs.unlinkSync(path)

delete file synchronous manner.

path - <String> or <Buffer>

Asynchronous file delete

require('fs'); - Load the File System module

delete file asynchronous manner.

var fs = require('fs');

fs.unlink('C:\\demo\\dog.jpg', function(error) {
    if (error) {
        throw error;
    }
    console.log('Deleted dog.jpg!!');
});

output

Deleted dog.jpg!!

Synchronous file delete

require('fs'); - Load the File System module

delete file synchronous manner.

var fs = require('fs');
fs.unlinkSync('C:\\demo\\dog.jpg');

Error if file not found

C:\javaworkspace\NodejsExamples\node-fs-example.js:5
  throw error;
  ^

Error: ENOENT: no such file or directory, unlink 'C:\demo\dog.jpg'
    at Error (native)
1 Comments
Avatar

Yogi Parmar

Hi Yashwant,
Could you please help or provide node.js program which deletes large sized folder which internally contains lots of sub folders?

Thanks
Parmar

Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]