Skip to main content
Writing a File using Node fs module

Writing and Deleting a File using Node fs module

in this post, We’ll extend our exploration of the Node.js fs module by diving into how to write and delete files. I have already shared a tutorial How To Get, Open, Read and Rename File Using Node fs, I am extending this post and adding write and delete file functionality.

How To Write a File

The fs.writeFile() method is used to asynchronously write the specified data to a file. This method will overwrite the file if a file already exists. It has an optional callback function to handle errors or success.

If you want to write into an existing file, then you should use another available method.

The syntax:
fs.writeFile(filename, data[, options], callback)

The above method accepts four parameters:

  • filename: It’s a string, a buffer, a URL, or a file description integer that indicates the location of the file to be written.
  • data: The data that will be written to the file.
  • options: It is a string or object that has three optional parameters: encoding, mode, flag.
  • callback: When the method is invoked, this is the function that will be called.
  • err: If the operation fails, this is an error that will be thrown.

The following code is to write a file in node.js.

// server.js
const fs = require('fs');

fs.writeFile('test.txt', 'console.log("hello!")', function (err) {
  if (err) throw err;
  console.log('New file test.txt is either created or if exists then updated');

In the above code, we create a file named test.txt with the provided content. If the file already exists, it will be overwritten. If not, a new file will be created.


New file test.txt is either created or if exists then updated

How To Delete a File

The fs.unlink() method is used to delete a file or symbolic link from the file system using the node fs module. This function isn’t applicable to directories. You can use fs.rmdir() method to remove a directory.

The syntax:
fs.unlink( path, callback )

The above method accept two parameters:

  • path: The path of the file that want to delete.
  • callback: When the method is invoked, this is the function that will be called.

The following code is to delete a file from a directory.

// server.js
const fs = require('fs');

fs.unlink('test.txt', function (err) {
  if (err) throw err;
  console.log("\nDeleted file: test.txt");

In the above code, We delete the test.txt file. If the file doesn’t exist, it will result in an error, so it’s a good practice to include error handling. It will remove the file from the disk.


Deleted file: test.txt

How To Delete All Files in a Directory using Nodejs

We can also delete all files of a directory using nodejs fs (File System) module. This module will be used to interact with the file system and the fs.readdir() and fs.unlink() functions.

Step 1: Import the fs module to access file system functions:

const fs = require('fs');

Step 2: Define the directory path from which you want to delete the files.

const directoryPath = '/path/to/your/directory';

Step 3: fs.readdir() function to read the contents of the directory:

fs.readdir(directoryPath, (err, files) => {
  if (err) {
    console.error('Error! unable to read directory:', err);

  // Iterate through the list of files
  for (const file of files) {
    // Construct the full file path
    const filePath = `${directoryPath}/${file}`;

    // Use the fs.unlink() function to delete the file
    fs.unlink(filePath, (err) => {
      if (err) {
        console.error('Error deleting file:', err);
      } else {
        console.log(`File ${file} has been deleted.`);

in the above code, we have the following sequence of actions executed:

  • It reads the contents of the specified directory.
  • It iterates through the list of files in the directory.
  • For each file, it constructs the full file path by concatenating the directory path and the file name.
  • It uses the fs.unlink() function to delete each file.

Please replace /path/to/your/directory with the actual directory path of your directory.

Leave a Reply

Your email address will not be published. Required fields are marked *