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.
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.
fs.readFile
. We pass 3 arguments—the file path relative to the home directory, the text encoding, and an arrow function.null
, an error has occurred. We log the error and return.string
containing all the file contents. We can print it to the console directly.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.