Steps to Create Node JS Application
Step 1: In the first step, we will create the new folder by using the below command in the VScode terminal.
mkdir folder-name
cd folder-name
Step 2: Initialize the NPM using the below command. Using this the package.json file will be created.
npm init -y
Project Structure:
Example 1: Below examples illustrate the fs.readFile() method in Node JS. The output is undefined it means the file is null. It starts reading the file and simultaneously executes the code. The function will be called once the file has been read meanwhile the ‘readFile called’ statement is printed then the contents of the file are printed.
//index.js
// Node.js program to demonstrate
// the fs.readFile() method
// Include fs module
var fs = require('fs');
// Use fs.readFile() method to read the file
fs.readFile('Demo.txt', 'utf8', function (err, data) {
// Display the file content
console.log(data);
});
console.log('readFile called');
Step to run the Node App:
node index.js
Output:
readFile called
undefined
Example 2: Below examples illustrate the fs.readFile() method in Node JS:
//index.js
// Node.js program to demonstrate
// the fs.readFile() method
// Include fs module
var fs = require('fs');
// Use fs.readFile() method to read the file
fs.readFile('demo.txt', (err, data) => {
console.log(data);
})
Step to run the Node App:
node index.js
Output:
undefined
Node JS fs.readFile() Method
In Node.js, the fs (File System) module furnishes a collection of methods for interacting with the file system. Among these methods, fs.readFile() stands out as a fundamental tool for reading data from files asynchronously. This article will delve into the fs.readFile() method, exploring its syntax, parameters, usage, and error handling.
Syntax:
fs.readFile( filename, encoding, callback_function )
Parameters:
The method accepts three parameters as mentioned above and described below:
- filename: It holds the file’s name to read or the entire path if stored at another location.
- encoding: It holds the encoding of the file. Its default value is ‘utf8’.
- callback_function: A callback function is called after reading the file. It takes two parameters:
- err: If any error occurred.
- data: Contents of the file.
Return Value:
It returns the contents/data stored in file or error if any.
Contact Us