Node.js | fs.readFileSync() Method

The fs.readFileSync() method is an inbuilt application programming interface of fs module which is used to read the file and return its content.

In fs.readFile() method, we can read a file in a non-blocking asynchronous way, but in fs.readFileSync() method, we can read files in a synchronous way, i.e. we are telling node.js to block other parallel process and do the current file reading process. That is, when the fs.readFileSync() method is called the original node program stops executing, and node waits for the fs.readFileSync() function to get executed, after getting the result of the method the remaining node program is executed.

Syntax:

fs.readFileSync( path, options )

Parameters:

  • path: It takes the relative path of the text file. The path can be of URL type. The file can also be a file descriptor. If both the files are in the same folder just give the filename in quotes.
  • options: It is an optional parameter which contains the encoding and flag, the encoding contains data specification. It’s default value is null which returns raw buffer and the flag contains indication of operations in the file. It’s default value is ‘r’.

Return Value: This method returns the content of the file.



Example 1:

  • input.txt file contents:
    This is some text data which is stored in input.txt file.
  • index.js file:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Node.js program to demonstrate the  
    // fs.readFileSync() method 
      
    // Include fs module
    const fs = require('fs');
       
    // Calling the readFileSync() method
    // to read 'input.txt' file
    const data = fs.readFileSync('./input.txt',
                {encoding:'utf8', flag:'r'});
      
    // Display the file data
    console.log(data);

    chevron_right

    
    

  • Output:
    This is some text data which is stored in input.txt file.
    

Now, the question is how is this fs.readFileSync() method is different from fs.readFile() method. An example where we can find out when to use fs.readFileSync() and fs.readFile() method.

Let’s say there are two input files input1.txt and input2.txt and both files are saved in the same folder.

Example 2:

  • input1.txt file contents:
    (1) This is some text data which is stored in input1.txt file.
  • input2.txt file contents:
    (2) This is some text data which is stored in input2.txt file.
  • index.js file:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Node.js program to demonstrate the  
    // fs.readFileSync() method 
      
    // Include fs module
    const fs = require('fs');
       
    // Callling the fs.readFile() method
    // for reading file 'input1.txt'
    fs.readFile('./input1.txt'
            {encoding:'utf8', flag:'r'},
            function(err, data) {
        if(err)
            console.log(err);
        else
            console.log(data);
    });
       
    // Calling the fs.readFileSync() method 
    // for reading file 'input2.txt'
    const data = fs.readFileSync('./input2.txt',
                  {encoding:'utf8', flag:'r'});
      
    // Display data
    console.log(data);

    chevron_right

    
    

  • Output:
    (2) This is some text data which is stored in input2.txt file.
    (1) This is some text data which is stored in input1.txt file.
    

Observation: We can observe that when we are calling the fs.readFile() method which reads ‘input1.txt’ and after that we are calling the fs.readFileSync() method which reads the ‘input2.txt’ file, but seeing the output we find that ‘input2.txt’ file is readed first then ‘input1.txt’ file, this happens because when the compiler compiles the node.js file it first calls the fs.readFile() method which reads a file, but parallely it continues to compile the remaining program too, after that it calls the fs.readFileSync() method which reads another file, when calling the readFileSync() method the compiler stops other parallel process (which is here reading the ‘input1.txt’ file from readFile() method) and continues the ongoing process to it’s end, whenever the ongoing process ends the compiler resumes the remaining process that’s why we observe that the contents of ‘input2.txt’ is printed first rather than ‘input1.txt’. So, we can use fs.readFileSync() method for tasks like pausing other parallel processes and read a file synchronously.

Reference: https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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 :

Be the First to upvote.


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