0
0
NodejsHow-ToBeginner · 3 min read

How to Use Buffer.from in Node.js: Syntax and Examples

In Node.js, Buffer.from creates a new buffer from a string, array, or another buffer. It converts data into a binary format that Node.js can work with efficiently.
📐

Syntax

The Buffer.from method creates a new buffer from different types of input data.

  • Buffer.from(string, encoding): Creates a buffer from a string using the specified encoding (default is 'utf8').
  • Buffer.from(array): Creates a buffer from an array of bytes (numbers 0-255).
  • Buffer.from(buffer): Copies an existing buffer.
javascript
Buffer.from(string[, encoding])
Buffer.from(array)
Buffer.from(buffer)
💻

Example

This example shows how to create buffers from a string, an array, and another buffer, then prints their contents and lengths.

javascript
const bufFromString = Buffer.from('Hello, Node.js!', 'utf8');
const bufFromArray = Buffer.from([72, 101, 108, 108, 111]);
const bufCopy = Buffer.from(bufFromString);

console.log(bufFromString.toString());
console.log(bufFromString.length);

console.log(bufFromArray.toString());
console.log(bufFromArray.length);

console.log(bufCopy.toString());
console.log(bufCopy.length);
Output
Hello, Node.js! 13 Hello 5 Hello, Node.js! 13
⚠️

Common Pitfalls

Common mistakes include:

  • Not specifying encoding when creating a buffer from a string, which defaults to 'utf8' but can cause issues if the string uses a different encoding.
  • Passing numbers outside the 0-255 range in an array, which will cause errors.
  • Using new Buffer() which is deprecated and unsafe; always use Buffer.from() instead.
javascript
/* Wrong: Using deprecated constructor */
// const buf = new Buffer('Hello'); // Avoid this

/* Right: Use Buffer.from */
const buf = Buffer.from('Hello', 'utf8');
📊

Quick Reference

UsageDescription
Buffer.from(string, encoding)Create buffer from string with encoding (default 'utf8')
Buffer.from(array)Create buffer from array of bytes (0-255)
Buffer.from(buffer)Create a copy of an existing buffer
Avoid new Buffer()Deprecated and unsafe, use Buffer.from() instead

Key Takeaways

Use Buffer.from() to safely create buffers from strings, arrays, or other buffers.
Always specify encoding when converting strings to buffers if not using UTF-8.
Avoid deprecated Buffer constructors like new Buffer().
Buffer.from(array) requires byte values between 0 and 255.
Buffers represent raw binary data useful for file and network operations.