a blog for those who code

Sunday, 19 March 2017

How to handle File Systems in Node.js

In this post we will be discussing about handling file systems in Node.js. Node.js installation comes with the file system module fs. fs provides a wrapper around standard POSIX functions. Compare to other languages, Node.js comes with minimum amount of bindings to provide full functionality of file system.

To use file system module in our application we need to import is using the require function as shown below :

var fs = require('fs');

Asynchronous and Synchronous Method for accessing File System


Almost each and every method of file system have both Synchronous and Asynchronous forms. You should try to use asynchronous method wherever possible because synchronous function can hamper the performance by stalling the Node's execution thread. The difference between asynchronous and synchronous method signature is in aynchronous form have a completion callback at the end and the first argument is reserved for exception whereas in synchronous form the exceptions are thrown immediatel and there is no concept of callback.

Example : Reading a file


var fs = require('fs');

//Asynchronous Way

fs.readFile('db.json', function (err, data) {
 if(err) throw err;
 console.log("The contents of file in Asynchronous way is " + data);
});

//Synchronous Way

var data = fs.readFileSync('db.json');
console.log("The contents of file in Synchronous way is " + data);

There are lot of methods in fs module which you can use to do any File I/O operations like :

fs.access - Which tests user's permission or file exixtence directly specified by path.
fs.appendFile - Append data to a file.
fs.chmod - Changes the mode of the file.
fs.chown - Changes the ownership of the file.
fs.close - Close a file descriptor.
fs.constants - It returns comonly used constants for file system operations.
fs.stat - Returns the information about the file.
fs.mkdir - Create a directory.
fs.open - Open file for reading (r), writing (w), appending (a).
fs.readdir - Read the contents of a directory.
fs.readFile - Reads the entire contents of a file.
fs.rename - Renames a file.
fs.rmdir - Delete a directory.
fs.truncate - Truncate a file to a specified length.
fs.watchFile - Watch for changes on filename.
fs.writeFile - Writes data to a file.

This post has introduced the Node.js file system module at a very high level. There are many more different functions on fs module which you can take advantage. For the word of caution I would suggest ignore the synchronous functions wherever possible.

ALSO READ : Reading and Writing to file simultaneouly in Nodejs

How to monitor a file for modifications in Node.js

var fs = require('fs');
var filePath = 'D:\\example\\file.txt';
var file = fs.readFileSync(filePath);
console.log('Initial File content : ' + file);
fs.watchFile(filePath, function() {
    console.log('File Changed ...');
    file = fs.readFileSync(filePath);
    console.log('File content at : ' + new Date() + ' is \n' + file);
});

How to get list of files in a directory in Node.js

var fs = require('fs');
fs.realpath(__dirname, function(err, path) {
 if (err) {
  console.log(err);
  return;
 }
 console.log('Path is : ' + path);
});

fs.readdir(__dirname, function(err, files) {
 if (err) return;
 files.forEach(function(f) {
  console.log('Files: ' + f);
 });
});

Please Like and Share the CodingDefined.com blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License