Sometimes, we want to read a file in Node.js.
In this article, we’ll look at how to read a file in Node.js.
How to read a file in Node.js?
To read a file in Node.js, we can use the fs.readFile
method.
For instance, we write
const fs = require('fs')
const path = require('path')
const filePath = path.join(__dirname, 'start.html');
fs.readFile(filePath, {
encoding: 'utf-8'
}, (err, data) => {
if (!err) {
console.log(data);
} else {
console.log(err);
}
});
to call fs.readFile
with the path of the file to read, an object with encoding
to read the file with the given encoding, and a callback that has the read file data
when the file is read.
We read the file at filePath
as a text file encoded with 'utf-8'
.
And then we get the file data from data
.
If err
is set, that means there’s an error when reading the file.
Conclusion
To read a file in Node.js, we can use the fs.readFile
method.