0
0
Node.jsframework~20 mins

Reading and writing buffer data in Node.js - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Buffer Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Buffer write and read code?
Consider the following Node.js code that writes a string to a buffer and then reads it back. What will be logged to the console?
Node.js
const buf = Buffer.alloc(10);
buf.write('hello');
console.log(buf.toString('utf8', 0, 5));
A"\u0000\u0000\u0000\u0000\u0000"
B"hello\u0000"
C"hellohello"
D"hello"
Attempts:
2 left
💡 Hint
Remember that Buffer.alloc creates a buffer filled with zeros and write returns the number of bytes written.
component_behavior
intermediate
2:00remaining
What happens when you slice a Buffer and modify the slice?
Given this code, what will be the output after modifying the slice?
Node.js
const buf = Buffer.from('abcdef');
const slice = buf.slice(1, 4);
slice[0] = 120;
console.log(buf.toString());
A"abxdef"
B"abcdef"
C"xbcdef"
D"axcdef"
Attempts:
2 left
💡 Hint
Buffer slices share the same memory as the original buffer.
📝 Syntax
advanced
2:00remaining
Which option correctly creates a Buffer from a hex string?
You want to create a Buffer from the hex string '48656c6c6f'. Which code snippet does this correctly?
ABuffer.from('48656c6c6f', 'utf8')
BBuffer.from('48656c6c6f', 'hex')
CBuffer.alloc('48656c6c6f', 'hex')
DBuffer.allocUnsafe('48656c6c6f')
Attempts:
2 left
💡 Hint
The encoding parameter tells Buffer how to interpret the string.
🔧 Debug
advanced
2:00remaining
Why does this Buffer write return 0 bytes written?
Look at this code snippet. Why does buf.write return 0?
Node.js
const buf = Buffer.alloc(5);
const bytesWritten = buf.write('hello world', 0, 5, 'utf8');
console.log(bytesWritten);
ABecause the string is longer than the buffer size, so nothing is written.
BBecause the length parameter is the max bytes to write, but the string is truncated and no bytes fit.
CBecause the length parameter is the max bytes to write, but the string is longer and write returns the number of bytes actually written.
DBecause the length parameter is less than the string length, so it writes only 5 bytes.
Attempts:
2 left
💡 Hint
Check the meaning of the length parameter in buf.write.
state_output
expert
3:00remaining
What is the final content of the buffer after these operations?
Analyze the code and determine the final string content of the buffer.
Node.js
const buf = Buffer.alloc(6);
buf.write('abc');
buf.write('def', 3);
buf.fill('x', 1, 4);
console.log(buf.toString());
A"axxxef"
B"axxxxf"
C"abcxxx"
D"abcdef"
Attempts:
2 left
💡 Hint
Remember that fill replaces bytes in the specified range, and write overwrites bytes starting at the given offset.