Node.js delete File example with unlink & unlinkSync – Rest API

In this tutorial, I will show you how to delete file in Node.js with unlink & unlinkSync method using Express for Rest API.

Related Posts:
Node.js File Upload/Download Rest API example
Google Cloud Storage with Node.js: File Upload example
How to upload multiple files in Node.js
Upload/store images in MySQL using Node.js, Express & Multer
How to upload/store images in MongoDB using Node.js, Express & Multer
Node.js Rest APIs example with Express, Sequelize & MySQL


Node.js delete File with unlink

To delete a file in Node.js, we can use the unlink() function offered by the Node built-in fs module. The method doesn’t block the Node.js event loop because it works asynchronously.

Here is an illustration showing how you can apply the technique:

const fs = require('fs');
fs.unlink(directoryPath + fileName, (err) => {
    if (err) {
        throw err;
    }
    console.log("Delete File successfully.");
});

Node.js delete File with unlinkSync

Another way to delete File in Node.js is using unlinkSync() (also provided by the Node built-in fs module). The Node.js event loop is blocked by this method until the action is finished. When you have many jobs running at once, it could harm performance.

const fs = require('fs');
try {
  fs.unlinkSync('file.txt');
  console.log("Delete File successfully.");
} catch (error) {
  console.log(error);
}

Node.js delete File Rest API

Overview

Our Node.js Application will provide Rest API for deleting a File by its name:
DELETE /files/[filename]

This is the static folder that stores all uploaded files:

node-js-delete-file-example-folder

If you want to implement upload/download file REST APIs like this:

MethodsUrlsActions
POST/uploadupload a File
GET/filesget List of Files (name & url)
GET/files/[filename]download a File
DELETE/files/[filename]delete a File

You can visit: Node.js File Upload/Download Rest API example

Technology

  • express 4.18.1
  • multer 1.4.4
  • cors 2.8.5

Project Structure

This is the project directory that we’re gonna build:

node-js-delete-file-example-project-structure

resources/static/assets/uploads: folder for storing uploaded files.
file.controller.js exports Rest API for deleting a File with url.
routes/index.js: defines routes for endpoints that is called from HTTP Client, use controller to handle requests.
server.js: initializes routes, runs Express app.

Setup Node.js Express File Upload project

Open command prompt, change current directory to the root folder of our project.
Install Express, CORS modules with the following command:

npm install express cors

Create Controller for file delete

In controller folder, create file.controller.js:

We will export remove() and removeSync() function that:

  • use fs.unlink / fs.unlinkSync function for deleting file by its name
  • return response with message
const fs = require("fs");
const remove = (req, res) => {
  const fileName = req.params.name;
  const directoryPath = __basedir + "/resources/static/assets/uploads/";
  fs.unlink(directoryPath + fileName, (err) => {
    if (err) {
      res.status(500).send({
        message: "Could not delete the file. " + err,
      });
    }
    res.status(200).send({
      message: "File is deleted.",
    });
  });
};
const removeSync = (req, res) => {
  const fileName = req.params.name;
  const directoryPath = __basedir + "/resources/static/assets/uploads/";
  try {
    fs.unlinkSync(directoryPath + fileName);
    res.status(200).send({
      message: "File is deleted.",
    });
  } catch (err) {
    res.status(500).send({
      message: "Could not delete the file. " + err,
    });
  }
};
module.exports = {
  remove,
  removeSync,
};

Define Route for deleting file

When a client sends HTTP requests, we need to determine how the server will response by setting up the routes.

Here is route with corresponding controller method:

  • DELETE /files/[fileName]: remove()

Create index.js file inside routes folder with content like this:

const express = require("express");
const router = express.Router();
const controller = require("../controller/file.controller");
let routes = (app) => {
  router.delete("/files/:name", controller.remove);
  app.use(router);
};
module.exports = routes;

You can see that we use controller from file.controller.js.

Create Express app server

Finally, we create an Express server in server.js:

const cors = require("cors");
const express = require("express");
const app = express();
global.__basedir = __dirname;
var corsOptions = {
  origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
const initRoutes = require("./src/routes");
app.use(express.urlencoded({ extended: true }));
initRoutes(app);
let port = 8080;
app.listen(port, () => {
  console.log(`Running at localhost:${port}`);
});

What we do are:
– import express and cors modules:

  • Express is for building the Rest apis
  • cors provides Express middleware to enable CORS with various options.

– create an Express app, then add cors middlewares using app.use() method. Notice that we set origin: http://localhost:8081.
– listen on port 8080 for incoming requests.

Run & Check

First we need to create uploads folder with the path resources/static/assets and files.

node-js-delete-file-example-folder

On the project root folder, run this command: node server.js.

Let’s use Postman to make HTTP DELETE request with a file name in url:

node-js-delete-file-rest-api-example

Check the result:

node-js-delete-file-example-result

Conclusion

Today we’ve learned how to delete File in Node.js using unlink and unlinkSync method along with Express Rest API.

If you want to implement upload/download file REST APIs, please visit:
Node.js File Upload/Download Rest API example

Upload to GCS:
Google Cloud Storage with Node.js: File Upload example

You can also know way to upload an Excel file and store the content in MySQL database with the post:
Node.js: Upload/Import Excel file data into Database

If you want to upload images into database, you can find instructions at:
Upload/store images in MySQL using Node.js, Express & Multer
How to upload/store images in MongoDB using Node.js, Express & Multer

Happy Learning! See you again.

Source Code

You can find the complete source code for this tutorial on Github.