Buffer.alloc expects a number for size, but '5' is a string.
Step 2: Understand type coercion in Buffer.alloc
Passing a string causes a TypeError because size must be a number.
Final Answer:
Buffer.alloc expects a number, not a string -> Option C
Quick Check:
Buffer.alloc('5') causes type error [OK]
Hint: Pass number, not string, to Buffer.alloc size [OK]
Common Mistakes:
Using string instead of number for size
Thinking Buffer.alloc needs 'new' keyword
Assuming length property is missing
5. You want to create a buffer from an array of bytes [72, 101, 108, 108, 111] representing 'Hello'. Which code correctly creates this buffer and converts it back to a string?
hard
A. const buf = Buffer.from([72,101,108,108,111]); console.log(buf.toString());
B. const buf = Buffer.alloc([72,101,108,108,111]); console.log(buf.toString());
C. const buf = Buffer.from('72,101,108,108,111'); console.log(buf.toString());
D. const buf = Buffer.alloc(5); buf.write([72,101,108,108,111]); console.log(buf.toString());
Solution
Step 1: Create buffer from array of bytes
Buffer.from(array) creates a buffer from an array of byte values correctly.
Step 2: Convert buffer back to string
buf.toString() converts the buffer bytes to the string 'Hello'.
Step 3: Analyze other options
Using 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.
Final Answer:
const buf = Buffer.from([72,101,108,108,111]); console.log(buf.toString()); -> Option A
Quick Check:
Buffer.from(array) + toString() = 'Hello' [OK]
Hint: Use Buffer.from(array) to create buffer from bytes [OK]