# Streams — Node.js

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

> Process data piece by piece instead of loading it all into memory.

## Readable & writable

A **readable** stream emits chunks of data (`data` events); a **writable** stream accepts chunks via `.write()`. Files, HTTP requests/responses, and process stdin/stdout are all streams.

## Piping a file

`pipe` connects a readable stream straight to a writable one — Node handles backpressure for you.

```javascript
import { createReadStream, createWriteStream } from "node:fs";

createReadStream("big-input.txt")
  .pipe(createWriteStream("copy.txt"));
```

**Quiz:** Why prefer streams over readFile for a very large file?

- [x] Streams process data in chunks instead of loading it all into memory
- [ ] Streams are always faster to write code for
- [ ] readFile cannot read files over 1KB

*Answer:* Streams process data in chunks instead of loading it all into memory. Streams keep memory usage low and let you start processing before the whole file has arrived.
