Summary - fs module
- Node.js course
- Beginner
- Lesson 105/116
- 5 min
Combine readFile, writeFile and existsSync to write a notes app.
Summary - the fs module
In this group you learned the Node.js fs module. fs/promises provides Promise-based methods; readFile reads, writeFile writes (overwriting), appendFile appends. For existence checks you use existsSync.
In async work you wait with await and catch errors with try/catch. writeFile erases old content; appendFile keeps it. appendFile is ideal for logs and readFile for reading config files.
Practice Your turn: writeFile + readFile
Start with import fs from 'fs/promises'. Define an async function run(). Inside, write await fs.writeFile('ozet.txt', 'hello'). Then read with const data = await fs.readFile('ozet.txt', 'utf8') and log with console.log(data). Call run().
Starter code
// Import fs/promises
// Define async function run
// Write with writeFile, read with readFile, log with console.log
// Call runSample solution
import fs from 'fs/promises';
async function run() {
await fs.writeFile('ozet.txt', 'hello');
const data = await fs.readFile('ozet.txt', 'utf8');
console.log(data);
}
run();Expected output
hello
Practice Your turn: log with appendFile
Start with import fs from 'fs/promises'. Define an async function run(). First write await fs.writeFile('log.txt', 'start'), then append with await fs.appendFile('log.txt', ' end'). Read with const data = await fs.readFile('log.txt', 'utf8') and log with console.log(data). Call run().
Starter code
// Import fs/promises
// Define async function run
// Start with writeFile, append with appendFile, read with readFile
// Call runSample solution
import fs from 'fs/promises';
async function run() {
await fs.writeFile('log.txt', 'start');
await fs.appendFile('log.txt', ' end');
const data = await fs.readFile('log.txt', 'utf8');
console.log(data);
}
run();Expected output
start end
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the fs methods
| Term | Meaning |
|---|---|
readFile |
reads a file |
writeFile |
overwrites |
appendFile |
appends |
existsSync |
existence check |
2 Which method fully replaces a file's content (overwrites)?
- fs.appendFile
- fs.writeFile Correct answer
- fs.readFile
- fs.existsSync
Explanation: writeFile erases old content and writes the new.