Delete a file in Node.js using fs (File System) module - unlink

Delete a file in Node.js using fs (File System) module

The fs module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions. It provides a lot of very useful functionality to access and interact with the file system. There is no need to install it because it is a part of the Node.js core. The fs module is responsible for all the asynchronous or synchronous file I/O operations.

To delete a file in Node.js we will use the unlink method of the fs module. It supports both synchronous and asynchronous methods. In the following example we created a simple server in order to test our app. So after getting a request we call the unlink method and return either the file is deleted or not.

1 Asynchronous usage of unlink in Node.js

const http = require("http");
var fs = require('fs');

const port = process.env.PORT || "3100";

const server = http.createServer(function (req, res) {
  //set content type
  res.writeHead(200, {"Content-Type": "text/html"});

  fs.unlink('file.txt', (err) => {
    if (err){
      // Handle the error
      if(err.code=='ENOENT'){
        res.write("File not found")
      }else{
        res.write("An error occured")
      }
    }else{
      // File successfully deleted
      res.write("successfully deleted")
    }

    // End the response
    res.end();
  });

}).listen(port);

2 Synchronous usage of unlink in Node.js

const http = require("http");
var fs = require('fs');

const port = process.env.PORT || "3100";

const server = http.createServer(function (req, res) {

  //set content type
  res.writeHead(200, {"Content-Type": "text/html"});

  try {

    // Delete file
    fs.unlinkSync('file.txt');
    res.write("successfully deleted")

  } catch (err) {

    // Handle the error
    if(err.code=='ENOENT'){
      res.write("File not found")
    }else{
      res.write("An error occured")
    }
    
  }

  // End the response
  res.end();

}).listen(port);