Site icon Tutorial

Reading from Files

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

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

Parameter Description:

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);

Exit mobile version