Node.js File System Module: The Complete Guide

The Node.js file system module allows you to work with a file system on your computer. We can include the File System module by using the require() method. 

The fs module provides the API for interacting with a file system in a manner closely modeled around standard POSIX functions. All node.js file system operations have synchronous and asynchronous forms. 

The asynchronous form always takes the completion callback as its last argument. The arguments passed to a completion callback depend on a method, but the first argument is always reserved for the exception.

The first argument would be null or undefined if the operation were accomplished.

Node js File System Module

The everyday use for the File System module is as follows.

  • Read files
  • Create files
  • Update files
  • Delete files
  • Rename files

Node.js as a File Server

We can require the fs module like the following code.

const fs = require('fs');

Let us take the example of a simple file system operation in which we remove the file from the disk.

Create one folder called filesystem and get inside that folder.

Now, create one file called acme.js inside the root for just demo purposes.

touch acme.js

We will delete this file using the fs module. So type the following code inside the server.js file.

// server.js

const fs = require('fs');

fs.unlink('acme.js', (err) => {
  if (err) throw err;
  console.log('File system operation successfully executed');
});

Now, run the following command in your terminal.

node server.js

It will give you the output like this, and your file will be deleted from the project.

Node js File System Module Example Tutorial

Using try-catch block

You can wrap the above operation in the try-catch block. Let us say we have already deleted the file, and again, we try to run the command to get the following error.

node fs module example

So, we need to define the try-catch error mechanism. Also, we need to perform the sync operation, not the async function.

// server.js

const fs = require('fs');

try {
    fs.unlinkSync('acme.js');
    console.log('File system operation successfully executed');
  }
catch(e) {
  console.log('Excecuted Catch block');
  console.log(e);
}

node filesystem example

So, we have used the fs module’s unlinkSync function.

#File paths

Using the file protocol, most fs operations accept file paths that may be specified as a string, a Buffer, or a URL object. 

String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as specified by the process.cwd().

Recreate the acme.js file inside the root. Then, write the following code inside the server file.

// server.js

const fs = require('fs');

fs.open('acme.js', 'r', (err, fd) => {
  if (err) throw err;
  console.log('File has opened');
  fs.close(fd, (err) => {
    console.log('File is closing');
    if (err) throw err;
  });
});

URL object support in the node fs module

The path or filename argument may be passed as a WHATWG URL object for most fs module functions. However, only URL objects using the file protocol are supported.

// server.js

const fs = require('fs');
const fileUrl = new URL('file:///acme.js');

fs.readFileSync(fileUrl);

Open a File using the Node fs module.

The syntax is following to open a file using the node fs module.

fs.open(path, flags[, mode], callback)

Flags

Flags for reading/writing operations are the following.

Flag Description
r Open a file for reading. An exception occurs if a file does not exist.
r+ Open a file for reading and writing. An exception occurs if the file does not exist.
rs Open a file for reading in synchronous mode.
rs+ Open a file for reading and writing, asking the OS to open it synchronously. See notes for ‘rs’ about using this with caution.
w Open a file for writing. The file is created (if it does not exist) or truncated (if it exists).
wx Like ‘w’ but fails if the path exists.
w+ Open a file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
wx+ Like ‘w+’ but fails if the path exists.
a Open a file for appending. The file is created if it does not exist.
ax Like ‘a’ but fails if the path exists.
a+ Open the file for reading and appending. The file is created if it does not exist.
ax+ Like ‘a+’ but fails if the path exists.

Let us consider opening a file using the node fs module.

// server.js

const fs = require('fs');

fs.open('acme.js', 'r+', function(err, fd) {
  if (err) {
     return console.error(err);
  }
 console.log("File opened successfully!");     
});

You can run the file and see the output. If the file exists, it will open in the mode of r+.

#Get File Information

Following is the syntax of the method to get the information about a  particular file. 

fs.stat(path, callback)

Let us take an example of node file stat.

// server.js

const fs = require('fs');

fs.stat('acme.js', function (err, stats) {
  if (err) {
      return console.error(err);
  }
  console.log(stats);
  console.log("Got file info successfully!");
  
  // Check file type
  console.log("isFile ? " + stats.isFile());
  console.log("isDirectory ? " + stats.isDirectory());    
});

Run and see the output in the terminal.

Get File Information in Node js

Writing a File using the Node fs module.

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

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

This method will overwrite the file if a file already exists. If you want to write into an existing file, you should use another method.

// server.js

const fs = require('fs');

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

#Reading a file using node fs module.

To read a file in node.js, you can use the following syntax.

fs.read(fd, buffer, offset, length, position, callback)

Let us take an example and understand how we can read the file using node fs.

// server.js

const http = require('http');
const fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('acme.js', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/js'});
    res.write(data);
    res.end();
  });
}).listen(8080);

The above code will spin up the http server and return the file’s content to the webpage. You can access the webpage at this URL: https://localhost:8080.

Rename Files.

To rename a file with the File System module,  use the fs. rename() method. The fs.rename() method renames the specified file.

// server.js

const fs = require('fs');

fs.rename('acme.js', 'paradox.js', function (err) {
  if (err) throw err;
  console.log('File Renamed!');
});

Delete Files

To delete a file with the File System module,  use the fs.unlink() method. The fs.unlink() method deletes the specified file.

// server.js

const fs = require('fs');

fs.unlink('paradox.js', function (err) {
  if (err) throw err;
  console.log('File deleted!');
});

Run the file, and the file will be removed from the disk.

That’s it.

1 thought on “Node.js File System Module: The Complete Guide”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.