Useful file operations in nodejs (Part-3)


Introduction

This is the third installment of the 5 part set of Useful file operations in nodejs. Please check its part-1 and part-2 before proceeding any further. It is recommended but the contents are not inter-related so do as it suits your requirements.




fs.open

It is used to open the file Asynchronously.The syntax of fs.open is fs.open(path, flags[, mode], callback) where [,mode] is optional. Their detailed explanation is as follows :

  • Path : The relative path of the file to be opened from the current working directory.
  • Flags : they can be one of the following : r, r+ , rs+ , w , w+ , wx , wx+ , a , a+ , ax , ax+
    • r : It is used to open the file for reading but an exception is caused if we try to open a file which does not exists.
    • r+ : It is used to open the file for reading and writing but an exception is caused if we try to open a file which does not exists.
    • rs+ : It is used to open the file for reading and writing in Synchronous mode.It also instructs the OS to bypass the local file system cache . Moreover it is recommended not to use it unless you have no other choce because it affects the I/O performance. And It will not transforms fs.open() into a synchronous function. If that is what you want , you must use fs.openSync() which is explained later in this article.

    • w : It is used to open the file for writing. It will create the file if the file is non-existing and also if the file with the given name exists it will truncate it that it will delete all its content and provide us with a empty file.

    • wx : Just like w, It is also used to open the file for writing. It will also create the file if the file is non-existing but if the file already exists it will fail and throw an error.


    • 		        
      //  you have to pass the Relative path of the file from the Current working directory.
      //The content to be appended is stored in variable "new_content" and it will be passed to the function.
      new_content = "This data will be appended at the end of the file.";
      
      fs.appendFile('data.txt', new_content , (err) => {
      	if(err) 
      		throw err;
      	console.log('The new_content was appended successfully');
      });
      
      // To check it's Asynchronous nature !
      console.log("This method is Asynchronous");
                      
      	            

      The output of the above code is :

      G:\nodejsera>node file.js
      This method is Asynchronous
      The new_content was appended successfully