Buffers
A Buffer holds raw binary data (bytes) — images, files, network data.
Buffer.from('Hello')— text to bytesbuf.toString('utf8'),buf.toString('base64')buf.length— size in bytes
Streams
A stream processes data piece by piece (chunks) instead of loading everything into memory. A 2 GB video can be sent with a few KB of memory.
| Type | Example |
|---|---|
| Readable | fs.createReadStream, an HTTP request |
| Writable | fs.createWriteStream, an HTTP response |
| Duplex | a network socket |
| Transform | gzip compression |
Connecting streams
Use pipeline() from node:stream/promises to connect streams. It handles errors and closes everything properly. (readable.pipe(writable) also works but does not handle errors well.)
Stream events
data, end, error, finish. You can also read a stream with for await (const chunk of stream).
Example
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
import { pipeline } from 'node:stream/promises';
console.time('gzip');
await pipeline(
createReadStream('server.log'), // read in chunks
createGzip(), // transform: compress
createWriteStream('server.log.gz'), // write in chunks
);
console.timeEnd('gzip');
console.log('Done: server.log.gz created');
// Buffers
const buf = Buffer.from('Namaste');
console.log(buf); // <Buffer 4e 61 6d 61 73 74 65>
console.log(buf.toString('base64')); // TmFtYXN0ZQ==
The log file is compressed using little memory however large it is. The Buffer lines show the raw bytes of "Namaste" and its base64 form.