Node.js - read file
In this article, we would like to show you how to read file in Node.js.
Node.js provides file operations API. You can import File System Module (fs) syntax with:
xxxxxxxxxx
const fs = require("fs")
Note:
fs
is a built-in module and you don't need to download it via npm.
Node.js file system module methods have asynchronous and synchronous versions:
- asynchronous
fs.readFile()
- recommended, - synchronous
fs.readFileSync()
.
The fs.readFile()
method takes in two parameters:
- path to the file,
- callback function with two arguments:
- error,
- data.
With fs.readFile()
method, we can read a file in a non-blocking asynchronous way.
The fs.readFileSync()
method takes in two parameters:
- path to the file,
- options (optional parameter).
With fs.readFileSync()
method, we can read files in a synchronous way, blocking other parallel node.js processes and do the current file reading process.
Below we create file.txt
with some text inside and file.js
to read the text. Then we simply use: node file.js
command in cmd to run our program.
file.txt
:
xxxxxxxxxx
message: dirask is cool.
file.js
:
xxxxxxxxxx
const fs = require('fs'); // imports File System Module
// Asynchronous reading
fs.readFile('file.txt', (error, data) => {
if (error) {
return console.error(error);
}
console.log('Asynchronous reading - ' + data.toString());
});
// Synchronous reading
const data = fs.readFileSync('file.txt');
console.log('Synchronous reading - ' + data.toString());
console.log('The program is executed. ');
Note:
Create your own
file.txt
andfile.js
eg. in Visual Studio Code, then run the script with the following command in the terminal / cmd:xxxxxxxxxx
1node file.js
Output:
xxxxxxxxxx
Synchronous reading - message: dirask is cool.
The program is executed.
Asynchronous reading - message: dirask is cool.