Concept Flow - Buffer allocation and encoding
Start
Allocate Buffer
Write Data with Encoding
Read or Use Buffer
End
This flow shows how Node.js allocates a buffer, writes data with a specific encoding, then reads or uses the buffer.
const buf = Buffer.alloc(5); buf.write('Hi', 'utf8'); console.log(buf); console.log(buf.toString('utf8'));
| Step | Action | Buffer Content (hex) | Buffer Content (string) | Notes |
|---|---|---|---|---|
| 1 | Allocate buffer of length 5 | 00 00 00 00 00 | Buffer initialized with zeros | |
| 2 | Write 'Hi' with utf8 encoding | 48 69 00 00 00 | Hi | 'H' = 0x48, 'i' = 0x69, rest zeros |
| 3 | Print buffer object | <Buffer 48 69 00 00 00> | Shows raw bytes in hex | |
| 4 | Convert buffer to string utf8 | 48 69 00 00 00 | Hi | Decodes entire buffer; null bytes (\u0000) included but non-printable in console |
| 5 | End | Process complete |
| Variable | Start | After Step 1 | After Step 2 | After Step 4 | Final |
|---|---|---|---|---|---|
| buf | undefined | <Buffer 00 00 00 00 00> | <Buffer 48 69 00 00 00> | <Buffer 48 69 00 00 00> | <Buffer 48 69 00 00 00> |
Buffer.alloc(size) creates a fixed-size buffer filled with zeros. Use buf.write(string, encoding) to write data into the buffer. Writing beyond buffer size truncates the string. buf.toString(encoding) decodes the entire buffer as string by default; null bytes become \u0000. Buffers hold raw bytes, useful for binary data handling in Node.js.