Concept Flow - Creating buffers
Start
Call Buffer.alloc(size)
Create zero-filled buffer
Return Buffer object
Use buffer data
End
This flow shows how calling Buffer.alloc(size) creates a new zero-filled buffer and returns it for use.
Jump into concepts and practice - no test required
const buf = Buffer.alloc(4);
console.log(buf);| Step | Action | Input | Buffer Content | Output |
|---|---|---|---|---|
| 1 | Call Buffer.alloc | 4 | ---- | Buffer of length 4 created |
| 2 | Initialize buffer bytes | N/A | <00 00 00 00> | Buffer filled with zeros |
| 3 | Return buffer | N/A | <00 00 00 00> | Buffer object returned |
| 4 | Console.log buffer | Buffer object | <00 00 00 00> | <Buffer 00 00 00 00> printed |
| 5 | End | N/A | <00 00 00 00> | Execution stops |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| buf | undefined | Buffer object (empty) | Buffer <00 00 00 00> | Buffer <00 00 00 00> | Buffer <00 00 00 00> |
Buffer.alloc(size) creates a new buffer of given size. The buffer is filled with zeros for safety. Returns a Buffer object you can use to store bytes. Use console.log to see buffer content as hex. Buffers are fixed size and hold raw binary data.
Buffer.alloc(10) do in Node.js?Buffer.alloc(size) creates a buffer of the given size filled with zeros.Buffer.from(string) creates a buffer from a string.Buffer.alloc expects a size number, new Buffer is deprecated, and Buffer.create does not exist.const buf = Buffer.from('abc');
console.log(buf.length);Buffer.from('abc') creates a buffer with bytes representing 'a', 'b', 'c'.const buf = Buffer.alloc('5');
console.log(buf.length);Buffer.alloc expects a number for size, but '5' is a string.Buffer.from(array) creates a buffer from an array of byte values correctly.buf.toString() converts the buffer bytes to the string 'Hello'.Buffer.alloc([72,101,108,108,111]) is wrong because alloc expects a number. Using Buffer.from('72,101,108,108,111') creates a buffer from the string of numbers, not bytes. Using buf.write([72,101,108,108,111]) is invalid as write doesn't accept arrays directly.