How to Read a File in Node JS?
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);
- How to Install Node Js and NPM Ubuntu?
- How to used Google ReCaptcha V3 in Node Js Express?
- How to Send Email with Attachment in Node js?
- How to Insert Data from Form into MySQL Database using Node js Express?
- Install Node Js and NPM Ubuntu 18.04/20.04/22.04 Tutorial
- How to Delete Data by id into MongoDB in Node JS?
- Install Node.js 16/17/18 on CentOS 8 Tutorial
- How to Upload File in MongoDB using Node js Express?