File handling in Node.js

The most important functionalities provided by programming languages is Reading and Writing files from the computers. Node.js provides the functionality to read and write files from the computer. Reading and Writing the file in Node.js is done by using one of the node.js cool module called fs module.
The fs module will install by using the given statement.

npm install fs --save

Note: The npm in the above commands stands for node package manager, a place from where we install all the dependencies. The –save flag is no longer needed after Node 5.0.0 version, as all the modules that we now install will be added to dependencies.

The file can be read and write in node.js in both Synchronous and Asynchronous way. A Synchronous method is a code blocking method which means the given method will block the execution of code until its execution is finished (i.e.Complete file is read or written). On the other hand, an Asynchronous method has a callback function which is executed on completion of execution of the given method and thus allows code to run during the completion of its execution. Thus, it is non-blocking.



Synchronous method to read the file: To read the file in a synchronous mode we use a method in fs module which is readFileSync(). It takes two parameters first is the file name with complete path and the second parameter is the character encoding which is generally ‘utf-8’.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Require the given module
var fs = require('fs');
  
// Use readFileSync() method
  
// Store the result (return value) of this
// method in a variable named readMe
  
// Keep the file in the same folder so
// donot need to specify the complete path
var readMe = fs.readFileSync('readMe.txt', 'utf-8');
  
// log the content of file stored in
// a variable to screen
console.log(readMe);

chevron_right


Output:

Synchronous method to writing into a file: To write the file in a synchronous mode we use a method in fs module which is writeFileSync(). It takes two parameters first is the file name with the complete path in which content is to be written and the second parameter is the data to be written in the file.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Require the given module
var fs = require('fs');
  
// Use readFileSync() method
  
// Store the result (return value) of this
// method in a variable named readMe
var readMe = fs.readFileSync('readMe.txt', 'utf-8');
   
// Store the content and read from
// readMe.txt to a file WriteMe.txt
fs.writeFileSync('writeMe.txt', readMe);

chevron_right


Asynchronous method to read and write from/into a file: To read/write the file in an asynchronous mode in fs module we use readFile() and writeFile() methods. The fs.readFile() takes three parameters first is the file name with the complete path, the second parameter takes the character encoding which is generally ‘utf-8’ and the third parameter is the callback function (which is fired after reading complete file) with two parameters, one is the error in case error occurred while reading file and second is the data that we retrieve after reading the file and the fs.writeFile() also takes three parameters, file name with its complete path, the second parameter is the data to be written in file and the third is a callback function which fires in case an error occurs while writing file.

Note: An Asynchronous method first completes the task (reading the file) and then fires the callback function.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Require the given module
var fs = require('fs');
   
// Use readFile() method
fs.readFile('readMe.txt', 'utf-8', function(err, data) {
   
    // Write the data read from readeMe.txt
    // to a file writeMe.txt
    if( !err )
        fs.writeFile('writeMe.txt', data, (err)=>{
            if( err ) {
                throw err;
            }
        });
    else
        throw err;
});

chevron_right


Output:



My Personal Notes arrow_drop_up

Hey, I am AkashdeepI am a third year undergraduate and currently pursuing a major in Computer Science and Engineering from ABES Engineering College, Ghaziabad, IndiaI have a problem solving mindset and I am interested in AlgorithmsI am preety handy with the tools such as HTML, CSS, Javascript,JQuerr

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.