Node.js delete File example
Tags: node, javascript, webdev, todayilearned
Published: 2022-08-22 07:52:04

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

This tutorial is from BezKoder:
https://www.bezkoder.com/node-js-delete-file/

<h2>Node.js delete File with unlink</h2>
To delete a file in Node.js, we can use the <code>unlink()</code> function offered by the Node built-in <strong>fs</strong> 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:

```js
const fs = require('fs');

fs.unlink(directoryPath + fileName, (err) => {
    if (err) {
        throw err;
    }

    console.log("Delete File successfully.");
});
```

<h2>Node.js delete File with unlinkSync</h2>
Another way to delete File in Node.js is using <code>unlinkSync()</code> (also provided by the Node built-in <strong>fs</strong> 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.

```js
const fs = require('fs');

try {
  fs.unlinkSync('file.txt');

  console.log("Delete File successfully.");
} catch (error) {
  console.log(error);
}
```

<h2>Node.js delete File Rest API</h2>
<h3>Overview</h3>
Our Node.js Application will provide Rest API for deleting a File by its name:
DELETE <code>/files/[filename]</code>

This is the static folder that stores all uploaded files:

![node-js-delete-file-example-folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/um0knhu22llyz5dxi19r.png)

If you want to implement upload/download file REST APIs like this:
<div class="table-responsive">
<table class="table table-hover  table table-hover" width="100%">
<thead>
<tr>
<th>Methods</th>
<th>Urls</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>POST</td>
<td>/upload</td>
<td>upload a File</td>
</tr>
<tr>
<td>GET</td>
<td>/files</td>
<td>get List of Files (name & url)</td>
</tr>
<tr>
<td>GET</td>
<td>/files/[filename]</td>
<td>download a File</td>
</tr>
<tr>
<td>DELETE</td>
<td>/files/[filename]</td>
<td>delete a File</td>
</tr>
</tbody>
</table>
</div>

You can visit: <a href="https://www.bezkoder.com/node-js-express-file-upload/">Node.js File Upload/Download Rest API example</a>

<h3>Technology</h3>
<ul>
	<li>express 4.18.1</li>
	<li>multer 1.4.4</li>
	<li>cors 2.8.5</li>
</ul>

<h3>Project Structure</h3>
This is the project directory that we're gonna build:

![node-js-delete-file-example-project-structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zpok0gwwzgakbq3rktoe.png)

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

<h3>Setup Node.js Express File Upload project</h3>
Open command prompt, change current directory to the root folder of our project.
Install Express, CORS modules with the following command:
<pre><code class="language-bash">npm install express cors
</code></pre>

<h3>Create Controller for file delete</h3>
In <strong>controller</strong> folder, create <em>file.controller.js</em>:

We will export <code>remove()</code> and <code>removeSync()</code> function that:
<ul>
	<li>use <code>fs.unlink</code> / <code>fs.unlinkSync</code> function for deleting file by its name</li>
	<li>return response with message</li>
</ul>

```js
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,
};
```


<h3>Define Route for deleting file</h3>
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:
<ul>
	<li>DELETE <code>/files/[fileName]</code>: <code>remove()</code></li>
</ul>

Create <em>index.js</em> file inside <strong>routes</strong> folder with content like this:

```js
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 <em>file.controller.js</em>.

<h3>Create Express app server</h3>
Finally, we create an Express server in <em>server.js</em>:

```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 <code>express</code> and <code>cors</code> modules:
<ul>
	<li>Express is for building the Rest apis</li>
	<li><a href="https://www.npmjs.com/package/cors">cors</a> provides Express middleware to enable CORS with various options.</li>
</ul>
- create an Express app, then add <code>cors</code> middlewares using <code>app.use()</code> method. Notice that we set origin: <code>http://localhost:8081</code>.
- listen on port 8080 for incoming requests.

<h3>Run & Check</h3>
First we need to create <strong>uploads</strong> folder with the path <code>resources/static/assets</code> and files.

![node-js-delete-file-example-folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/um0knhu22llyz5dxi19r.png)

On the project root folder, run this command: <code>node server.js</code>.

Let's use <strong>Postman</strong> to make HTTP DELETE request with a file name in url:

![node-js-delete-file-rest-api-example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w5ucbam2c3v0x8kj4o2i.png)

Check the result:

![node-js-delete-file-example-result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sz1u2zjtf2l6r0holkx0.png)

<h2>Conclusion</h2>
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:
<a href="https://www.bezkoder.com/node-js-express-file-upload/">Node.js File Upload/Download Rest API example</a>

Upload to GCS:
<a href="https://bezkoder.com/google-cloud-storage-nodejs-upload-file/">Google Cloud Storage with Node.js: File Upload example</a>

You can also know way to upload an Excel file and store the content in MySQL database with the post:
<a href="https://bezkoder.com/node-js-upload-excel-file-database/">Node.js: Upload/Import Excel file data into Database</a>

If you want to upload images into database, you can find instructions at:
- <a href="https://bezkoder.com/node-js-upload-image-mysql/">Upload/store images in MySQL using Node.js, Express & Multer</a>
- <a href="https://bezkoder.com/node-js-upload-store-images-mongodb/">How to upload/store images in MongoDB using Node.js, Express & Multer</a>

Happy Learning! See you again.

<h2>Source Code</h2>
You can find the complete source code for this tutorial on <a href="https://github.com/bezkoder/express-file-upload">Github</a>.