Node.js How to Convert String to Buffer Easily
Buffer.from(yourString), which creates a buffer containing the string's bytes.Examples
How to Think About It
Algorithm
Code
const str = "hello"; const buf = Buffer.from(str); console.log(buf);
Dry Run
Let's trace converting the string "hello" to a buffer.
Input string
str = "hello"
Convert to buffer
buf = Buffer.from(str) results in
Output buffer
console.log(buf) prints
| Step | Value |
|---|---|
| 1 | "hello" |
| 2 | |
| 3 | Printed 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
const str = "hello"; const buf = Buffer.alloc(str.length); buf.write(str); console.log(buf);
const str = "hello"; const buf = new Buffer(str); console.log(buf);
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.
| Approach | Time | Space | Best 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 |
Buffer.from() to convert strings to buffers safely and clearly.new Buffer() constructor instead of Buffer.from().