Reading Files Synchronously with fs.readFileSync()
You'll learn when and how to use blocking file reads in Node.js for startup tasks.
What Makes It Synchronous?
While fs.readFile() reads files asynchronously (non-blocking), fs.readFileSync() is the blocking version. When you call it, your entire program pauses and waits until the file is completely read before moving to the next line of code.
Think of it like waiting in line at a coffee shop: with the synchronous approach, you stand there doing nothing until your order is ready. No multitasking, no moving forward until it's done.
Basic Syntax
const fs = require('fs');
const configData = fs.readFileSync('./config.json', 'utf8');
console.log(configData);
console.log('This runs only after the file is read');
The method takes two arguments:
- File path (string)
- Encoding (optional, but typically
'utf8'for text files)
Without encoding, you get a raw Buffer object instead of a readable string.
When to Use It
Use fs.readFileSync() for startup configuration and initialization code where:
- Your app needs data before it can proceed
- You're loading config files during startup
- Execution order must be guaranteed
- The file read happens once at the beginning
Avoid it in request handlers or repeated operations—blocking code during runtime freezes your entire server!
Practical Example
const fs = require('fs');
// Good: Loading config at startup
const config = JSON.parse(fs.readFileSync('./config.json', 'utf8'));
const port = config.port || 3000;
console.log(`Starting server on port ${port}`);
Key Takeaway: fs.readFileSync() blocks execution until the file is read—perfect for startup tasks, but dangerous in production code where blocking operations freeze your application.