Performance: Reading and writing buffer data
This concept affects how fast Node.js can process binary data streams and file I/O operations, impacting server responsiveness and throughput.
Jump into concepts and practice - no test required
const fs = require('fs'); const readStream = fs.createReadStream('file.bin'); const writeStream = fs.createWriteStream('file-copy.bin'); readStream.pipe(writeStream);
const fs = require('fs'); fs.readFile('file.bin', (err, data) => { if (err) throw err; const str = data.toString('utf8'); // process string const newBuffer = Buffer.from(str, 'utf8'); fs.writeFile('file-copy.bin', newBuffer, (err) => { if (err) throw err; }); });
| Pattern | CPU Usage | Memory Usage | Event Loop Blocking | Verdict |
|---|---|---|---|---|
| Buffer to string conversion and back | High (extra encoding/decoding) | High (extra buffer copies) | Blocks event loop during conversion | [X] Bad |
| Direct buffer streaming with pipe() | Low (minimal CPU overhead) | Low (no extra copies) | Non-blocking, asynchronous | [OK] Good |
Buffer in Node.js?Buffer.alloc(size) creates a zero-filled buffer.Buffer.new and Buffer.create do not exist; new Buffer() is deprecated and unsafe.const buf = Buffer.from('abc');
console.log(buf[1]);Buffer.from('abc') creates a buffer with ASCII codes of 'a', 'b', 'c'. Index 1 is 'b'.const buf = Buffer.alloc(3);
buf.write('hello');
console.log(buf.toString());src to another buffer dest starting at index 2 in dest. Which code correctly does this?source.copy(target, targetStart, sourceStart, sourceEnd).src starting at 0 to 4 bytes, into dest starting at index 2.