Home
Node.js
fs readFile Example
Updated Dec 25, 2023
Dot Net Perls
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.
fs writeFile
fs createReadStream
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.
function
Example. We must include the "node:fs" type and we can do this with a require statement. This is like a "using" directive in other languages.
Step 1 We invoke fs.readFile. We pass 3 arguments—the file path relative to the home directory, the text encoding, and an arrow function.
Step 2 If the first argument to the lambda is not null, an error has occurred. We log the error and return.
Step 3 The data is a string containing all the file contents. We can print it to the console directly.
Step 4 We can split apart the file based on any delimiter. Here we split it on newlines, and get the lines in an array.
String split
Array
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).
Home
Changes
© 2007-2025 Sam Allen