Topic 33 of 55
File (fs) Read/Write Synchronous
Overview
The `fs` module interacts with the file system. Synchronous methods (like `readFileSync`) block the Node.js event loop until the file operation completes. They are useful for quick scripts or reading configuration files during app startup, but should never be used during web server requests.
Syntax
javascript
const fs = require('fs');
try {
// 1. Reading a file (Blocks execution until finished)
// If you omit 'utf8', it returns a Buffer instead of a string
const data = fs.readFileSync('./config.json', 'utf8');
console.log(data);
// 2. Writing to a file (Overwrites existing content)
fs.writeFileSync('./log.txt', 'Application started at ' + new Date());
// 3. Appending to a file
fs.appendFileSync('./log.txt', '\nAnother log entry.');
} catch (err) {
// Synchronous methods throw standard try/catch errors
console.error("File system error:", err.message);
}Common Pitfalls
- Using `readFileSync` inside an Express route handler will literally freeze your entire server for ALL users until that file is read.
- Synchronous functions don't return errors; they `throw` them. Always wrap them in a `try...catch` block to prevent the app from crashing.
Real-World Example
Loading a configuration file synchronously before starting a server:
example
javascript
const fs = require('fs');
const express = require('express');
let config;
try {
// It's perfectly fine to block the thread HERE,
// because the server hasn't started accepting requests yet.
const rawConfig = fs.readFileSync('./app-config.json', 'utf8');
config = JSON.parse(rawConfig);
} catch (err) {
console.error("FATAL: Could not load configuration file.");
process.exit(1);
}
const app = express();
app.listen(config.port, () => console.log('Server started'));