NodeJS File Systems

NodeJS File Systems: To get access to the physical file system the NodeJS provides the “fs” module. The “fs” module is used for I/O operations that may be either synchronous or Asynchronous.

Let’s consider some I/O operations using the “fs” module.

NodeJS File Systems – Reading File

To read any file asynchronous in the “fs” module then use fs.readFile() method.

fs.readFile() Syntax

fs.readFile (fileName,[,options],callback)

fs.readFile() Parameters Explanation

  • filename: To provide path and name of the file as string
  • options: To include encoding and flag as object or string. The default values of these encoding-utf8 and flag-“r”.
  • callback: This function has two parameters i.e. err and fd and these get called after completion of reading operations.

fs.readFile() Example

vas fs=require('fs')
fs.readFile('TextFile.txt',function(err,data){
if(err)throw err;
console.log(data);
});

In the above example, the TestFile.txt will be called and executes the callback function when the read operation completes. If the code id good then it will works successfully otherwise throw an error. the “err” parameter specifies the error information and the “data” parameter defines the content of the specified file.

TextFile.txt File

The TextFile.js contains the following information

“Sample file to test the fs module of Node JS.”

fs.readFile() Example Output

Exception handling eventful output

Reading File Synchronously

To read files synchronously in the “fs” module of Node JS use fs.readFileSync() method.

fs.readFileSync() Example

var fs= require('fs');
var data=fs.readFileSync(testfile.txt','utf8);
console.log(data);

NodeJS File Systems – Writing a File

To write data to the file in the “fs” module of Node JS use fs.writeFile() method. It writes the data if the file already exists otherwise it creates a new file and writes data.

fs.writeFile() Syntax

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

fs.writeFile() Parameters Explanation

  • filename: to provide full path and name of file as string.
  • Data: The content that should be written in a file.
  • options: To include encoding and flag as object or string. The default values of these encoding-utf8 and flag-“r”.
  • callback: This function has two parameters i.e. err and fd and these get called after completion of write operations.

fs.writeFile() Example

var fs = require('fs');
fs.writeFile('test.txt', 'Hello World!', function (err) {
if (err)
console.log(err);
else
console.log('Write operation complete.');
});

fs.appendFile() Example

As same to the fs.writeFile() method you can add data in existing file use fs.appendFile() method.

var fs = require('fs');
fs.appendFile('test.txt', 'Hello World!', function (err) {
if (err)
console.log(err);
else
console.log('Append operation complete.');
});

NOTE: Now open the file “test.txt” and check the data is appended or not.

NodeJS File Systems – Opening a File

To open a file for read or write operation then use fs.open() method.

fs.open() Syntax

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

fs.open() Parameters Explanation

  • path: to provide full path with name of file as string.
  • Flag: The flag is used to perform operations.
  • Mode: the mode specifies read, write, read-write, etc. the default to 0666 for read-write.
  • callback: This function has two parameters i.e. err and fd and these get called after completion of file open operation.

File System Flags

The Flags that are used to read or write operations are listed below.

Flag Description
r To open the file for reading and an exception rises if the file not exists.
r+ To open the file for reading and writing and exception rises if the file not exists.
rs To open a file in synchronous mode.
rs+ To open a file for reading and writing and specifying to open synchronously.
w To open a file in writing mode. The file will create if it doesn’t exist or truncate if the file exists.
wx Same as “w” but it will fail if the path exists.
w+ To open a file for reading and writing. The file will create if it doesn’t exist or truncate if the file exists.
wx+ Same as “w+” but it will fail if the path exists.
a To open the file for appending and the file is created if it doesn’t exist.
ax Same as “a” but it will fail if the path exists.
a+ To open the file for reading and appending and the file is created if it doesn’t exist.
ax+ Same as “a+” but it will fail if the path exists.

Example to Read Content in Existing File

var fs = require('fs');
fs.open('TestFile.txt', 'r', function (err, fd) {
if (err) {
return console.error(err);
}
var buffr = new Buffer(1024);
fs.read(fd, buffr, 0, buffr.length, 0, function (err, bytes) {
if (err) throw err;
// Print only read bytes to avoid junk.
if (bytes > 0) {
console.log(buffr.slice(0, bytes).toString());
}
// Close the opened file.
fs.close(fd, function (err) {
if (err) throw err;
});
});
});

NodeJS File Systems – Delete File

To delete particular existing file use fs.unlink() method.

fs.unlink() Syntax

fs.unlink (path, callback);

fs.unlink() Example

var fs = require('fs');
fs.unlink('test.txt', function () {
console.log('write operation complete.');
});

fs Module Important Methods

Method Description
fs.readFile(fileName  [,options], callback) To read existing file.
fs.writeFile(filename, data[, options], callback) To write to the file and if file exists then it will overwrites the content otherwise creates a new files.
fs.open(path, flags[, mode], callback) To open file for reading and writing
fs.rename(oldPath, newPath, callback) To renames an existing file.
fs.chown(path, uid, gid, callback) For Asynchronous chown
fs.stat(path, callback) To return fs.stat object that includes important file statistics.
fs.link(srcpath, dstpath, callback) To links file asynchronously.
fs.symlink(destination, path[, type], callback) To Symlink asynchronously.
fs.rmdir(path, callback) To rename an existing directory.
fs.mkdir(path[, mode], callback) To create a new directory
fs.readdir(path, callback) To read the content of particular directory.
fs.utimes(path, atime, mtime, callback) To change the timestamp of file.
fs.exists(path, callback) To know file exists or not.
fs.access(path[, mode], callback) To tests a user’s permission for particular file.
fs.appendFile(file, data[, options], callback) To append new content to the existing file.