Reading from Files

Use fs.readFile() method to read the physical file asynchronously.

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

Parameter Description:

  • 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.

The following example demonstrates reading existing TestFile.txt asynchronously.

Example: Reading File

var fs = require(‘fs’);

fs.readFile(‘TestFile.txt’, function (err, data) {

if (err) throw err;

console.log(data);

});

The above example reads TestFile.txt (on Windows) asynchronously and executes callback function when read operation completes. This read operation either throws an error or completes successfully. The err parameter contains error information if any. The data parameter contains the content of the specified file.

The following is a sample TextFile.txt file.

TextFile.txt

This is test file to test fs module of Node.js

Now, run the above example and see the result as shown below.

C:\> node server.js

This is test file to test fs module of Node.js

Use fs.readFileSync() method to read file synchronously as shown below.

Example: Reading File Synchronously

var fs = require(‘fs’);

var data = fs.readFileSync(‘dummyfile.txt’, ‘utf8’);

console.log(data);

Share this post
[social_warfare]
File Operations
Writing and Updating Files

Get industry recognized certification – Contact us

keyboard_arrow_up