ReadFile. With Node.js, we can manipulate files on the local file system—we can read and write files. And the easiest way to read a file is with fs.readFile.
With a require statement, we include the "node:fs" type. Then we can call methods on the "fs" type such as readFile. We can nest a lambda expression (an arrow function) to handle the IO results.
const fs = require("node:fs");
// Step 1: specify the file path, and a lambda expression that is called when the IO is done.
fs.readFile("programs/example.txt", "ascii", (err, data) => {
// Step 2: handle errors with an if-statement.
if (err) {
console.error(err);
return;
}
// Step 3: display the file contents.
console.log(data);
// Step 4: split apart the file on newlines and print its lines.
let lines = data.split("\n");
console.log(lines);
});Line 1
Line 2
Line 3
[ 'Line 1', 'Line 2', 'Line 3' ]
ReadFileSync. This method reads a file in 1 line of code—it is not asynchronous and does not require a callback function. It is probably best to use it for smaller files.
const fs = require("node:fs");
// Read file in 1 line of code with readFileSync.
let result = fs.readFileSync("programs/example.txt");
console.log("Length:", result.length);
console.log(result.toString());Length: 18
Some example text.
With the methods on the fs type in Node.js, we can handle files in an efficient way. We can read files (as with the fs.readFile method) and write files—along with other file system tasks.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 25, 2023 (new example).