Reading Files
The fs module is the built-in module for working with files. Fs is short for file system.
Reading a file at once
This reads notes.txt as text and prints it.
const fs = require("fs");
const text = fs.readFileSync("notes.txt", "utf8");
console.log(text);Reading without waiting
This reads the same file without waiting. The callback prints the text when the read ends.
fs.readFile("notes.txt", "utf8", (error, text) => {
if (error) return;
console.log(text);
});A missing file
This tries a file that does not exist. The error check prints Read failed.
fs.readFile("missing.txt", "utf8", (error, text) => {
if (error) {
console.log("Read failed");
}
});Example
const fs = require("fs");
const text = fs.readFileSync("notes.txt", "utf8");
console.log(text);Key points
- Use require("fs") to load the fs module.
- readFileSync reads a whole file at once.
- Sync means the program waits for the read to end.
- The second input, utf8, tells Node to read the file as text.
- readFile reads a file without waiting.
- readFile uses a callback with an error first.
- Check the error first inside the callback.
In this example, notes.txt is a small text file with two lines. The program reads the whole file at once. The second input, utf8, asks for text. The print shows both lines. Make notes.txt first with a text editor.
Note
Sync reading blocks the program, so use it for small files.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which method reads a file and waits for the read to end?