What fs Provides
The fs module gives Node.js scripts direct access to the file system — something browser JavaScript can't do for security reasons. It offers callback-based, promise-based, and synchronous versions of most operations.
Reading a File (Promises)
Console Output
Click “Run” to see the console output here.
Writing a File
Console Output
Click “Run” to see the console output here.
Three API Styles
| Style | Example | When to Use |
|---|---|---|
| Promise-based | fs/promises → await readFile() | Preferred in modern async code |
| Callback-based | fs.readFile(path, cb) | Older code, or APIs that require callbacks |
| Synchronous | fs.readFileSync(path) | Startup scripts, CLIs — blocks the event loop, use sparingly |
Common File Operations
Console Output
Click “Run” to see the console output here.
Avoid Synchronous fs Calls in a Server
readFileSync() blocks the entire event loop until the disk read completes — fine for a one-off CLI script, but disastrous in a running web server, where it would freeze every other in-flight request.
Best Practice
Default to the fs/promises API with async/await in application code — it reads cleanly and never blocks the event loop, unlike the synchronous variants.