MyInternships.in

Core Modules

Node.js Buffer

A Buffer is a fixed-length chunk of binary data outside the JavaScript heap. Node uses buffers for file contents, network packets, images and anything else that is not text.


What is Buffer in Node.js?

A Buffer is a fixed-length chunk of binary data outside the JavaScript heap. Node uses buffers for file contents, network packets, images and anything else that is not text.

Buffer example

Creating and converting buffers
JavaScript
const buf = Buffer.from('Hello Node', 'utf8');
console.log(buf);                 // <Buffer 48 65 6c 6c 6f ...>
console.log(buf.length);          // bytes, not characters
console.log(buf.toString('base64'));
console.log(Buffer.from('SGk=', 'base64').toString('utf8'));  // 'Hi'

const empty = Buffer.alloc(10);   // zero-filled, safe

Key points to remember

  • buf.length counts bytes — a multi-byte character counts as several.
  • Buffer.alloc zero-fills; Buffer.allocUnsafe is faster but may expose old memory.
  • Reading a file without an encoding returns a Buffer.
  • Buffer.from(string) is the modern replacement for the removed new Buffer().

Common mistakes with Buffer

  • Using allocUnsafe and sending the uninitialised contents somewhere.
  • Slicing a multi-byte string by byte offset and corrupting the characters.

Node.js Buffer— Interview Questions & FAQs

What is a Buffer in Node.js?+

A fixed-length container for raw binary data stored outside the V8 heap. It exists because JavaScript strings cannot represent arbitrary bytes safely.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships