DEV Community

Cover image for How to convert a String to Buffer and vice versa in Node.js
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to convert a String to Buffer and vice versa in Node.js

Originally posted here!

Convert String to Buffer

To convert a string to a Buffer, you can use the from() method from the global Buffer class in Node.js.

// a string
const str = "Hey. this is a string!";

// convert string to Buffer
const buff = Buffer.from(str, "utf-8");

console.log(buff); // <Buffer 48 65 79 2e ... 72 69 6e 67 21>
Enter fullscreen mode Exit fullscreen mode
  • The method accepts a valid string as the first argument.
  • and an optional encoding as the second argument.

Convert Buffer to String

To convert a Buffer to a String, you can use the toString() in the Buffer object.

// buffer
const str = "Hey. this is a string!";
const buff = Buffer.from(str, "utf-8");

// convert buffer to string
const resultStr = buff.toString();

console.log(resultStr); //Hey. this is a string!
Enter fullscreen mode Exit fullscreen mode

Feel free to share if you found this useful 😃.


Top comments (0)