Node.js How to Convert Buffer to String Easily
In Node.js, convert a Buffer to a string by calling
buffer.toString(), optionally passing the encoding like buffer.toString('utf8').Examples
InputBuffer.from('Hello')
OutputHello
InputBuffer.from([72, 101, 108, 108, 111])
OutputHello
InputBuffer.from('48656c6c6f', 'hex')
OutputHello
How to Think About It
To convert a Buffer to a string, think of the Buffer as a container holding bytes. You use the Buffer's built-in
toString() method to translate those bytes into readable text, specifying the encoding if needed.Algorithm
1
Get the Buffer object you want to convert.2
Call the <code>toString()</code> method on the Buffer.3
Optionally, pass the encoding type like 'utf8' to <code>toString()</code>.4
Return the resulting string.Code
nodejs
const buffer = Buffer.from('Hello, world!'); const str = buffer.toString('utf8'); console.log(str);
Output
Hello, world!
Dry Run
Let's trace converting Buffer.from('Hello') to string.
1
Create Buffer
buffer =
2
Call toString()
buffer.toString('utf8') returns 'Hello'
3
Print result
Output is 'Hello'
| Step | Buffer Content | String Result |
|---|---|---|
| 1 | ||
| 2 | Hello | |
| 3 | Hello |
Why This Works
Step 1: Buffer holds bytes
A Buffer stores raw bytes, which are not human-readable text.
Step 2: toString() converts bytes
The toString() method reads the bytes and converts them into a string using the specified encoding.
Step 3: Encoding matters
Using the correct encoding like utf8 ensures the bytes map correctly to readable characters.
Alternative Approaches
Using TextDecoder
nodejs
const { TextDecoder } = require('util'); const decoder = new TextDecoder('utf8'); const buffer = Buffer.from('Hello'); console.log(decoder.decode(buffer));
TextDecoder is a modern API that can decode buffers with more control but requires importing from 'util'.
Buffer to JSON then stringify
nodejs
const buffer = Buffer.from('Hello'); const json = buffer.toJSON(); const str = String.fromCharCode(...json.data); console.log(str);
This method converts buffer to JSON and then to string but is less efficient and more complex.
Complexity: O(n) time, O(n) space
Time Complexity
Converting a Buffer to string requires reading each byte once, so it is O(n) where n is the buffer length.
Space Complexity
The output string requires space proportional to the buffer size, so O(n) extra space.
Which Approach is Fastest?
Using buffer.toString() is the fastest and simplest method; alternatives add overhead or complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| buffer.toString() | O(n) | O(n) | Simple and fast conversion |
| TextDecoder.decode() | O(n) | O(n) | More control over decoding |
| Buffer to JSON then String.fromCharCode | O(n) | O(n) | Rarely used, less efficient |
Always specify encoding in
toString() to avoid unexpected results.Forgetting to specify encoding or assuming Buffer is already a string causes wrong output.