How to read file using nodejs

 Posted On  | Yashwant Chavan 

In this tutorial, You will learn how to read file using nodejs. This example covers reading file content in asynchronous (non-blocking) and synchronous (blocking) manner.

syntax - (Asynchronous read)

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

Asynchronously reads the entire contents of a file. The callback is passed two arguments (err, data), where data is the contents of the file. If no encoding is specified, then the raw buffer is returned

file <String> | <Buffer> | <Integer> filename or file descriptor

options <Object> | <String>. encoding <String> | <Null> default = null, flag <String> default = 'r'

callback - <Function>

syntax - (Synchronous read)

fs.readFileSync(file[, options])

Synchronously reads the entire contents of a file. If no encoding is specified, then the raw buffer is returned.

file <String> | <Buffer> | <Integer> filename or file descriptor

options <Object> | <String>. encoding <String> | <Null> default = null, flag <String> default = 'r'

hello.txt file content

one
two
three
...
...
...
ten

Read file in asynchronously

var fs = require('fs');

fs.readFile('c:\\hello.txt', 'utf8', function(error, data) {
    if (error) {
        console.log('Error:- ' + error);
        throw error;
    }
    console.log(data);
});

output

one
two
three
...
...
...
ten

Read file in synchronously

var fs = require('fs');

var data = fs.readFileSync('c:\\hello.txt', 'utf8');
console.log(data);

output

one
two
three
...
...
...
ten


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0297 seconds.