How to delete file using nodejs

 Posted On  | Yashwant Chavan 

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.

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)


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0409 seconds.