0
0
NodejsHow-ToBeginner · 2 min read

Node.js How to Convert String to Buffer Easily

In Node.js, convert a string to a buffer using Buffer.from(yourString), which creates a buffer containing the string's bytes.
📋

Examples

Input"hello"
Output<Buffer 68 65 6c 6c 6f>
Input"Node.js Buffer"
Output<Buffer 4e 6f 64 65 2e 6a 73 20 42 75 66 66 65 72>
Input""
Output<Buffer >
🧠

How to Think About It

To convert a string to a buffer in Node.js, think of a buffer as a container for raw bytes. You want to take the characters of the string and store their byte values in this container. Node.js provides a simple method to do this conversion directly, so you just pass the string to that method and get the buffer back.
📐

Algorithm

1
Get the input string you want to convert.
2
Use the built-in method to create a buffer from the string.
3
Return or use the resulting buffer as needed.
💻

Code

nodejs
const str = "hello";
const buf = Buffer.from(str);
console.log(buf);
Output
<Buffer 68 65 6c 6c 6f>
🔍

Dry Run

Let's trace converting the string "hello" to a buffer.

1

Input string

str = "hello"

2

Convert to buffer

buf = Buffer.from(str) results in

3

Output buffer

console.log(buf) prints

StepValue
1"hello"
2
3Printed output:
💡

Why This Works

Step 1: Buffer.from() creates a buffer

The Buffer.from() method takes a string and converts it into a buffer containing the raw bytes of that string.

Step 2: String encoding defaults to UTF-8

By default, the string is encoded in UTF-8, so each character is converted to its UTF-8 byte representation.

Step 3: Buffer holds raw bytes

The resulting buffer holds these bytes, which can be used for binary operations or network communication.

🔄

Alternative Approaches

Using Buffer.alloc and writing string
nodejs
const str = "hello";
const buf = Buffer.alloc(str.length);
buf.write(str);
console.log(buf);
This method manually allocates buffer space and writes the string, less concise but useful for custom buffer sizes.
Using new Buffer() constructor (legacy)
nodejs
const str = "hello";
const buf = new Buffer(str);
console.log(buf);
This is legacy and deprecated; use Buffer.from() instead for safety and clarity.

Complexity: O(n) time, O(n) space

Time Complexity

The conversion processes each character once to encode it into bytes, so time grows linearly with string length.

Space Complexity

A new buffer is created to hold the bytes, so space usage is proportional to the string size.

Which Approach is Fastest?

Buffer.from() is the fastest and safest method compared to manual allocation or legacy constructors.

ApproachTimeSpaceBest For
Buffer.from()O(n)O(n)Simple, safe string to buffer conversion
Buffer.alloc() + write()O(n)O(n)Custom buffer sizes or partial writes
new Buffer() (legacy)O(n)O(n)Legacy code, avoid in new projects
💡
Always use Buffer.from() to convert strings to buffers safely and clearly.
⚠️
Using the deprecated new Buffer() constructor instead of Buffer.from().