Reading and Writing Files (the fs module)
Save and load text on disk with Node.js
fs ("file system") module gives you the tools. This is how programs remember things after they stop running.
- load the
fsmodule withrequire, - read a file as text and write text back,
- tell the difference between synchronous, callback, and promise styles,
- choose the right style for the job.
1. Meet the fs module
The fs module is built into Node — you do not install anything. You just require it at the top of your file:
const fs = require('fs');
Now the variable fs holds many helpful functions, such as readFileSync, readFile, writeFileSync, and appendFileSync. Notice that some names end in Sync and some do not — that difference is the heart of this lesson.
2. Reading a file (synchronous)
The simplest way to read is fs.readFileSync. The word Sync means "synchronous": Node stops and waits until the whole file is read, then hands you the result.
const fs = require('fs');
// Read the whole file, THEN continue
const text = fs.readFileSync('poem.txt', 'utf8');
console.log(text);
// Output:
// Roses are red,
// Node reads files fast.
Always pass 'utf8' as the second argument. Without it, Node gives you a Buffer (raw bytes shown as numbers) instead of a readable string. With 'utf8', you get normal text you can print.
Because it waits, the next line only runs after the file is fully read. Simple to think about — but Node can do nothing else while it waits.