Node.js Tutorial – File System

The tutorial provides the detail about the node.js file processing mechanism. The node.js fs module provides the I/O operations modeled around standard POSIX functions. The fs module can be accessed using the below command:

const fs = require('fs');

synchronous and asynchronous form in the node.js file system

The node.js fs module provides the support for synchronous asynchronous forms. The exceptions occured in the synchronous forms are thrown immediately using the try…catch { } . The Asynchronous forms provides arguments where last arguments always returns the callback. The first arguments is available for capturing the exception. If there is no exception then first argument will be returned as null /undefined.

Place the file at the location and mention it in the sample program for asynchronous form execution

const fs = require('fs');
fs.unlink('/tmp/test-fs-async/remove-async-file.txt', (err) => {
  if (err) throw err;
  console.log('The file removed successfully from the path -/tmp/test-fs-async/remove-async-file.txt');
});

sample program for the synchronous form execution

const fs = require('fs');

try {
  fs.unlinkSync('/tmp/test-fs-async/remove-async-file.txt');
   console.log('The file removed successfully from the path -/tmp/test-fs-async/remove-async-file.txt');
} catch (err) {
  // code for handling error 
}

Node.js asynchronous ordering

In case of asynchronous execution, the ordering of methods is not guaranteed. In the below given example related to the file renaming, if we call fs.stat() operation before the fs.rename() then it could lead to error.

fs.rename('/tmp/test-fs-async/remove-async-file.txt', '/tmp/world', (err) => {
  if (err) throw err;
  fs.stat('/tmp/test-fs-async/sync-file.txt', (err, stats) => {
    if (err) throw err;
    console.log(`stats: ${JSON.stringify(stats)}`);
  });
});

Node.js File System Flags

The fs module provides below given syntax for opening the file

fs.open(path, flags[, mode], callback)    where
path: path string with the file name

flags: depicts the behavior of the file to be opened.

mode: sets the file mode if the file was created. It defaults to 0666, readable and writable.

callback: This is the callback function which gets two arguments (err, fd)

The below given are the commonly used file system flags.

File System FlagFile system flag Description
‘a’allows to append the opened file. In case file does not exist, it created the file with the name specified.
‘ax’ similar functioning as ‘a’ but fails execution if path exists
‘a+’ allows to open the file for reading and it can be appended. In case file does not exist, it created the file with the name specified.
‘ax+’ similar functioning as ‘a+’ but fails execution if path exists
‘as’ allows to append the opened file for reading in the synchronous mode. In case file does not exist, it created the file with the name specified.
‘as+’allows to open the file for reading and it can be appended in the synchronous mode. In case file does not exist, it created the file with the name specified.
‘r’allows to open the file for ready. Gives error in case file does not exist.
‘r+’ allows to open file for reading and writing. Gives error in case file does not exist.
‘rs+’allows to open file for reading and writing in synchronous mode and instruct operating system to bypass the local file system cache.
‘w’allows to open file for writing . In case file does not exist, it creates the file.
‘wx’similar functioning as ‘w’ but fails execution if path exists
‘w+’allows to open file for reading and writing . In case file does not exist, it creates the file.
‘wx+’similar functioning as ‘w+’ but fails execution if path exists

File information using node.js file system

The below given syntax provides the file related information

fs.stat(path, callback)  , where

path: path string with the file name

callback: This is the callback function which gets two arguments (err, stats)

fs stats class methods in node.js file system

fs stat class methodsfs stat class method description
stats.isfile()returns true if file type is normal file.
stats.isdirectory() returns true if file type is directory
stats.isblockdevice() returns true if file type is of a block device
stats.ischaracterdevice() returns true if file type is of a character device
stats.issymboliclink() returns true if file type is of symbolic link
stats.isfifo() returns true if file type is of fifo ( file-in-file-out)
stats.isscoket() returns true if file type is of a socket

Node.js fs promises API

The node.js fs promises API provides and alternate approach than calling asynchronous file system methods. It returns the promise object than using the callbacks. The promises API can be accessed using the below given command:

require(‘fs’).promises