Node.js Streams & Buffers 1 — Questions and Answers
Question 1: What is the default string encoding used when creating a Buffer from a string in Node.js?
- utf8 (Correct answer)
- ascii
- base64
- latin1
Correct answer: utf8
Node.js uses 'utf8' as the default encoding when no encoding argument is provided to Buffer.from().
Question 2: Which Node.js stream type is used exclusively for reading data?
- Writable
- Duplex
- Readable (Correct answer)
- Transform
Correct answer: Readable
Readable streams are data sources you can consume — examples include fs.createReadStream() and HTTP request objects.
Question 3: What method connects a Readable stream to a Writable stream so data flows automatically?
- readable.connect(writable)
- readable.pipe(writable) (Correct answer)
- readable.forward(writable)
- writable.receive(readable)
Correct answer: readable.pipe(writable)
The pipe() method on a Readable stream automatically forwards chunks to the destination Writable stream and manages backpressure.
Question 4: What is the key difference between Buffer.alloc(size) and Buffer.allocUnsafe(size)?
- allocUnsafe is faster but may contain old memory data; alloc zero-fills the buffer (Correct answer)
- alloc is faster but may contain old memory data; allocUnsafe zero-fills the buffer
- They behave identically in modern Node.js versions
- allocUnsafe throws an error if sufficient memory is unavailable
Correct answer: allocUnsafe is faster but may contain old memory data; alloc zero-fills the buffer
Buffer.alloc() initializes memory to zero for safety, while Buffer.allocUnsafe() skips initialization for speed but may expose old process memory.
Question 5: In Node.js streams, what is 'backpressure'?
- An error thrown when a stream closes unexpectedly
- A flow-control mechanism that slows the producer when the consumer cannot keep up (Correct answer)
- A compression technique applied before data is transmitted
- The event emitted when a Readable stream buffer overflows
Correct answer: A flow-control mechanism that slows the producer when the consumer cannot keep up
Backpressure prevents memory exhaustion by signaling the data producer to pause when the consumer's internal buffer is full.
Question 6: How do you convert a Node.js Buffer to a UTF-8 encoded string?
- buffer.stringify()
- buffer.decode('utf-8')
- buffer.toString('utf8') (Correct answer)
- String.fromBuffer(buffer)
Correct answer: buffer.toString('utf8')
The toString() method on a Buffer accepts an encoding argument and returns the decoded string; 'utf8' is the default if omitted.
Question 7: What event does a Readable stream emit after all data has been consumed and the stream has closed?
- 'close'
- 'finish'
- 'done'
- 'end' (Correct answer)
Correct answer: 'end'
The 'end' event fires when there is no more data to be consumed from the Readable stream, signaling EOF.
What is the default string encoding used when creating a Buffer from a string in Node.js?