Home
Map
fs readFile ExampleRead files from the disk as strings with the fs readFile method, handling errors. Get lines from the file.
Node.js
This page was last reviewed on Dec 25, 2023.
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 path to the file, 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 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).
Home
Changes
© 2007-2024 Sam Allen.