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.
Jump into concepts and practice - no test required
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.
Buffer.alloc(5) do in Node.js?Buffer.alloc(size) creates a buffer of the given size and fills it with zeros for safety.Buffer.alloc(5) creates a buffer of length 5 filled with zeros.'hello' using UTF-8 encoding?Buffer.from() creates a buffer from a string with encoding.Buffer.from('hello', 'utf8') is correct syntax; Buffer.alloc does not accept string input, and Buffer.create does not exist. new Buffer() is deprecated.const buf = Buffer.from('abc', 'utf8');
console.log(buf.length);buf.length is 3.const buf = Buffer.alloc(5, 'abc'); console.log(buf.toString());
Buffer.alloc(size, fill) accepts a size and a fill value. The fill can be a string, which repeats to fill the buffer.toString() converts buffer back to string.'café' and then convert it back to a string. Which encoding should you use to preserve the accented character correctly?'utf8' ensures the accented character is preserved when converting to and from buffer.