EN
Node.js - read file as text (UTF-8)
3
points
In this article, we would like to show you how to read file as text using Node.js.
Quick solution:
const fs = require('fs');
const text = fs.readFileSync('/path/to/file.txt', 'utf-8');
or:
const fs = require('fs');
fs.readFile('/path/to/file.txt', 'utf-8', (error, text) => {
// Something here ...
});
Note: to know different text encoding check this article.
Practical example
In this section you can find two examples that shows how to read example file.txt
file as text. First example reads file.txt
file synchronously and second one asynchronously.
Example file.txt
file:
Line 1
Line 2
Line 3
Sync mode
Example index.js
file:
const fs = require('fs');
try {
const text = fs.readFileSync('file.txt', 'utf-8');
console.log(text);
} catch (error) {
console.error(text);
}
Output:
Line 1
Line 2
Line 3
Async mode
Example index.js
file:
const fs = require('fs');
fs.readFile('file.txt', 'utf-8', (error, text) => {
if (error) {
console.error(error); // or `throw error;`
} else {
console.log(text);
}
});
Output:
Line 1
Line 2
Line 3