# The fs Module — Node.js

Source: https://www.geekswithgeeks.com/en/nodejs/node-fs

> Reading and writing files, synchronously or asynchronously.

## Reading a file

The async, Promise-based API lives under `fs/promises`.

```javascript
import { readFile } from "node:fs/promises";

const text = await readFile("notes.txt", "utf8");
console.log(text);
```

## Writing a file

`writeFile` creates or overwrites the file completely.

```javascript
import { writeFile } from "node:fs/promises";

await writeFile("out.txt", "Hello, file!\n");
console.log("saved");
```

Output:

```
saved
```

## Sync vs async

`readFileSync` blocks the entire event loop until done — fine at startup, risky inside a server handling requests. Prefer the async version there.

**Quiz:** Why avoid `readFileSync` inside a request handler?

- [ ] It throws on missing files
- [x] It blocks the event loop for every other request
- [ ] It cannot read text files

*Answer:* It blocks the event loop for every other request. Sync fs calls freeze Node's single thread — no other request is served until the read finishes.
