How to get the length of the string as bytes in Nodejs?
Published September 24, 2020
To get the string length in bytes in Node.js, you can use the byteLength()
method in the Buffer
class.
Let's say you have a string called Hello World!
,
// string
const str = "Hello World!";
Now let's use the Buffer.byteLength()
to get the bytes of the string.
// string
const str = "Hello World!";
// get string length in bytes
const bytes = Buffer.byteLength(str, "utf-8");
console.log(bytes); // 12
- The method accepts types of
Buffer
,String
, etc as the first argument. - The second argument is the encoding, the default is
utf-8
. - The method returns the size of the bytes as an
integer
.
See this example live in repl.it.