gotchajavascriptCritical
Buffer.from() vs deprecated new Buffer()
Viewed 0 times
Buffer.from/alloc available since Node.js 5.10
Buffer deprecationnew BufferBuffer.fromBuffer.allocuninitialized memorysecurity
nodejs
Error Messages
Problem
new Buffer(input) is deprecated and has a security vulnerability. If input is a number, it allocates uninitialized memory that may contain sensitive data from other processes.
Solution
Use the explicit Buffer.from() / Buffer.alloc() / Buffer.allocUnsafe():
// String to buffer
const buf = Buffer.from('hello', 'utf8');
// Allocate zeroed buffer (safe)
const zeroed = Buffer.alloc(1024);
// Allocate uninitialized (fast but unsafe)
const fast = Buffer.allocUnsafe(1024);
fast.fill(0); // zero it manually if needed
// From array
const arr = Buffer.from([0x68, 0x65, 0x6c]);
// NEVER: new Buffer(size) — leaks memory contents
// NEVER: new Buffer(userInput) — if userInput is a number, leaks memory
// String to buffer
const buf = Buffer.from('hello', 'utf8');
// Allocate zeroed buffer (safe)
const zeroed = Buffer.alloc(1024);
// Allocate uninitialized (fast but unsafe)
const fast = Buffer.allocUnsafe(1024);
fast.fill(0); // zero it manually if needed
// From array
const arr = Buffer.from([0x68, 0x65, 0x6c]);
// NEVER: new Buffer(size) — leaks memory contents
// NEVER: new Buffer(userInput) — if userInput is a number, leaks memory
Why
new Buffer(n) allocated n bytes of uninitialized memory. An attacker could pass a large number to read contents of previously freed memory, potentially containing passwords or keys. Buffer.alloc() zeros the memory; Buffer.from() is for creating buffers from data.
Gotchas
- Buffer.allocUnsafe() is faster but contains old memory — only use when you'll immediately fill it
- Buffer.from(string) defaults to UTF-8 encoding
- Buffer.isBuffer() to check if something is a Buffer
- In ESM, Buffer is available globally — no import needed
Code Snippets
Safe Buffer usage
// BAD: deprecated, security risk
const buf = new Buffer(100); // uninitialized memory!
// GOOD: explicit allocation
const safe = Buffer.alloc(100); // zeroed
const data = Buffer.from('hello'); // from stringContext
When working with binary data in Node.js
Revisions (0)
No revisions yet.