File Reading and Writing Operations

In every language or tool, reading and writing file are most important task, Node.js includes fs module to access physical file system.

The fs module is responsible for all the asynchronous or synchronous file I/O operations.

In order to use these functionalities we need to require the fs module as shown below

var fs = require('fs');

We perform below operation in our day to day life in file system, similarly NodeJs helps perform those operations.

  • Read files
  • Create files
  • Update files
  • Delete files
  • Rename files
  • Create & Delete & Rename Folders
We can perform all the above operation in two ways in Nodejs,
  • Asynchronously : Synchronous communication requires a response back before continuing to the next task/person, that means once the operation is done then only next line of code will get executed
  • Synchronously : Asynchronous communication does not require a response back before continuing to the next task /person, execution of one line will not halt the execution of the next line, so execution would be faster

Read a File in Nodejs

Asynchronously reading file :

We can read the file in asynchronously using the fs.readFile() method from the fs module.

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

filename: Full path and name of the file as a string, it could be an relative or absolute path.

options: The options parameter can be an object or string which can include encoding and flag. The default encoding is utf8 and default flag is "r".

callback: A function with two parameters err and fd, and will get called when readFile operation completes. Function body will be executed after reading the file

Reading the file Asynchronously on nodejs:

// import fs module
var fs=require('fs');

fs.readFile('sample-file.txt', (err, data) => {
	if (err) 
		throw err;
	console.log("Content of the file :  " + data);

Reading the file Synchronously :

Other development language people will find the synchronous file-reading operation clearer because it is similar to the one they have been working with.

Synchronous kind of file reading will halt the execution till file reading operation is complete, for small file we donot have much time lag but when we have huge file please do prefer asynchronous way reading the file

var fs = require('fs');
// name of the file
var filename = 'sample-file.txt'; 
var contentSync = fs.readFileSync(filename);
console.log('Content of the file : ' + contentSync);

Write a File in Nodejs

Writing the file Asynchronously :

writeFile() function writes the content to the file without stopping the execution of other line of code.

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

filename: Full path and name of the file as a string.

options: The options parameter can be an object or string which can include encoding and flag. The default encoding is utf8 and default flag is "r".

callback: A function with two parameters err and fd. This will get called when readFile operation completes.

Writing file asynchronously in node js:

//Writing a File Asynchronously using nodejs
var fs =  require('fs');
var content= "this is the content in the file";
fs.writeFile('sample-write.txt', content , (err) => {
	if (err) 
		throw err;
	console.log('File saved!');

Writing the file Synchronously :

writeFileSync() writes the file in Synchronous way but it will block the execution of the other lines Writing the file Synchronously :

var fs = require('fs');

var content-sync = "Synchronously writing with node.js";

fs.writeFileSync('sample-write-sync.txt.txt', content-sync);
console.log("File saved");

Append a File using Nodejs

Appending the file Asynchronously :

fs.appendFile() function appends given content to a file, the file will be created if the file does not exist,

								fs.appendFile(path, data[, options], callback)

Appending the file asynchronously with nodejs

//import fs module
var fs = require('fs');
new_data = "add me at the end of the file with Async.";
fs.appendFile('append-file.txt', new_data , (err) => {
		throw err;
	console.log('Append success');

Appending the file Synchronously :

Similar to writing and reading operation we also append a file using the nodejs with appendFileSync() function Appending the file synchronously

//file append operation in nodejs
var fs = require('fs');
var content = "add me at the end of the file with sync in nodejs;
fs.appendFileSync('append-file.txt', content);
console.log("Append Success");

Rename a File in Nodejs

Renaming the file Asynchronously :

rename() methods renames the file name in asynchronously

var fs = require('fs');

fs.rename('file-name.txt', 'new_name.txt', (err) => {
	if (err)
		throw err;
	console.log('Renamed successfully');

Renaming the file Synchronously :

renameSync() renames the file in synchronously by blocking the other code, which mean till renaming is complete nodejs will not execute next line of code.

var fs =  require('fs');
//Relative path of the file
fs.renameSync('data.txt', 'newData.txt');
console.log('File renamed successfully');

// To check it's Synchronous nature !
console.log("This method is Synchronous");

Delete a File in Nodejs

Deleting the file Asynchronously :

Use fs.unlink() method to delete an existing file from the folder

var fs = require('fs');
var filename = 'content.txt';
fs.unlink(filename, (err) => {
	console.log('File deleted ...');

Deleting the file Synchronously :

unlinkSync() function deletes a file in synchronously

var fs = require('fs');
var filename = 'data.txt';
console.log('File Deleted ..!');

Folder operations in Nodejs

  • To create a new directory, you can use the fs.mkdir() or fs.mkdirSync() method.
  • fs.mkdir(path[, mode], callback) : create new folder
  • fs.exists(path, callback) : check whether a file exists or not
  • To rename a directory with the File System module, use the fs.rename(oldPath, newPath, callback) method.
    const fs = require('fs');
    var old_directory ='./source';
    var new_directory ='./target';
    fs.rename(old_directory, new_directory, (err)=>{
      if(err) throw err;

Fun Facts - Not really

  • fs.readFile() : Read file in asynchronous way.
  • fs.readFileSync() : Read file in synchronous way.
  • fs.writeFile() : Write file in asynchronous way.
  • fs.writeFileSync() : Write file in synchronous way.
  • fs.appendFile() : Append file in asynchronous way.
  • fs.appendFileSync() : Append file in synchronous way.
  • fs.rename() : Rename file name in asynchronous way.
  • fs.renameSync() : Rename file name in synchronous way.
  • fs.unlink() : Delete file in asynchronous way.
  • fs.unlinkSync() : Delete file in synchronous way.

About Author

Article is written by Pavan (a) KarthiQ. Well, I am serving notice period in an MNC, Bangalore. I thought to enrich every person knowledge a little, I always have a feeling, when we teach something, we will learn more than what you know. Knowledge is the only thing that doubles when you spend it.

I have also created the reporter for Protractor Jasmine. Use for your projects without any hesitation

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions