12-Jan-2023
.
Admin
Hello Friends,
In this post, we will discuss the the Node JS Platform “fs” module. FS Stands for File System. This module is also known as IO or FileSystem or Stream module.
This article is focused on how to read a file in node js. In this article, we will implement a reading file with node.js. We will look at an example of reading a file in node.js. This tutorial will give you a simple example of a complete guide for reading files in node.js. So, let's follow a few steps to create an example of the ultimate guide to reading files in node.js.
For this tutorial; you need to create a new text file name myfile.txt and update the following text in this file:
myfile.txt file content
php
java
nodejs
javascript
ruby
python
Node.js fs.readFile() Method
There are two functions to read files in the node js. The first function readFile() and another part is readFileSync(). The first function reads the data of the file asynchronously. The second function reads the file’s data synchronously.
readFile() function
The readFile() function reads the file’s data asynchronous.
Syntax
fs.readFile(file[, options], callback)
Example – Node JS Read file asynchronously
var fs = require('fs');
fs.readFile('c:\\myfile.txt', 'utf8', function(error, data) {
if (error) {
console.log('Error:- ' + error);
throw error;
}
console.log(data);
});
readFileSync() function
The readFileSync() function reads the file’s data Synchronous.
Syntax
fs.readFileSync(file[, options])
Example – Node JS Read file in synchronously
var fs = require('fs');
var data = fs.readFileSync('c:\\myfile.txt', 'utf8');
console.log(data);
I hope it can help you...
#Node JS