EN
Node.js - read files
0
points
In this article, we would like to show you how to read files in Node.js.
Below we will present 3 methods to read files in node.js:
- synchronously,
- asynchronously with callback,
- asynchronously with async/await.
Synchronously
Is recommended to use synchronous operations when we want to get better performance - e.g. Node JS-based sequential scripts run under the operating system.
const fs = require('fs');
const data = fs.readFileSync('/path/to/file.txt','utf8');
console.log(data);
Asynchronously with callback
Note:
In the
fs.readFile()
method, we must provide an absolute path to the file.
const fs = require('fs');
fs.readFile('/path/to/file.txt', 'utf8', (error, data) => { // encoding parameter is optional
if (error) throw error;
console.log(data);
}
);
Asynchronously with async/await
const { readFile } = require('fs/promises');
const readFileAsync = async (path) => {
try {
const data = await readFile(path, 'utf-8'); // encoding parameter is optional
console.log(data);
} catch (error) {
console.error(error);
}
};
readFileAsync('/path/to/file.txt');