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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 25, 2023 (new example).