DevAcademy
LearnNode.jsThe File System (fs) Module
BeginnerNode.js

The File System (fs) Module

Read, write, and manage files with Node.js's built-in fs module.

Reading Time

14 min

Lesson

Lesson 7 of 34

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)

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Writing a File

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Three API Styles

StyleExampleWhen to Use
Promise-basedfs/promises → await readFile()Preferred in modern async code
Callback-basedfs.readFile(path, cb)Older code, or APIs that require callbacks
Synchronousfs.readFileSync(path)Startup scripts, CLIs — blocks the event loop, use sparingly

Common File Operations

Try it yourself — edit and run

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.

Interview Questions

Quick Quiz

1. Why can't browser JavaScript directly read arbitrary files from disk, but Node.js can?

2. Why should readFileSync() be avoided in a running web server?

3. What does fs/promises provide?