In Node.js, why do we need buffers instead of just using strings for all data?
Think about data like images or files that are not text.
Buffers are needed because strings in JavaScript are designed for text data and use UTF-16 encoding. They cannot represent raw binary data like images, audio, or files accurately. Buffers provide a way to work with this raw binary data efficiently.
Consider a buffer containing raw binary data. What is the likely result if you convert it directly to a string without specifying encoding?
const buf = Buffer.from([0xff, 0xfe, 0xfd]); const str = buf.toString(); console.log(str);
Think about how binary data maps to text characters.
When converting a buffer to a string without specifying encoding, Node.js uses UTF-8 by default. Raw binary data may not map correctly to UTF-8 characters, resulting in garbled or unreadable output, but no error is thrown.
Which of the following code snippets correctly creates a buffer from the string 'hello'?
Remember that some older methods are deprecated.
Buffer.from() is the modern and recommended way to create a buffer from a string. The 'new Buffer()' constructor is deprecated and unsafe. The other methods do not exist.
What is the length of the buffer created from the string 'café' using Buffer.from('café')?
const buf = Buffer.from('café'); console.log(buf.length);
Consider how UTF-8 encodes accented characters.
The string 'café' has 4 characters, but the 'é' character is encoded as two bytes in UTF-8. So the buffer length is 5 bytes.
Given the code below, why does the output not show the expected combined buffer content?
const buf1 = Buffer.from('Hello');
const buf2 = Buffer.from('World');
const combined = buf1 + buf2;
console.log(combined.toString());const buf1 = Buffer.from('Hello'); const buf2 = Buffer.from('World'); const combined = buf1 + buf2; console.log(combined.toString());
Think about how '+' works with objects in JavaScript.
The '+' operator converts buffers to strings '[object Object]' before concatenation, so the output is '[object Object][object Object]'. To concatenate buffers properly, use Buffer.concat([buf1, buf2]).