Languages
[Edit]
EN

JavaScript - convert string to bytes array under Node.js

9 points
Created by:
Richard-Bevan
413

In this short article, we would like to show, how using JavaScript, convert string to bytes array under Node.js.

Quick solution:

const buffer = Buffer.from(string, 'utf8');     // where `buffer` has `Buffer` type

or:

const buffer = Buffer.from(string, 'utf16le');  // where `buffer` has `Buffer` type

 

Practical examples

Hint: converting string to bytes you need to select the encoding type that should be used to produce bytes array.

1. to UTF-8 bytes:

const toBytes = (string) => Array.from(Buffer.from(string, 'utf8'));


// Usage example:

const bytes = toBytes('Some text here...');

console.log(bytes);

Note: go to this article to see pure JavaScript solution.

Output:

[
   83, 111, 109, 101, 32, 116, 101, 120, 116, 32, 104, 101, 114, 101, 46,  46,  46
]

 

2. to UTF-16 LE bytes:

const toBytes = (string) => Array.from(Buffer.from(string, 'utf16le'));


// Usage example:

const bytes = toBytes('Some text here...');

console.log(bytes);

Output:

[
  83,   0, 111,   0, 109,   0, 101,   0,  32,   0, 116,   0, 101,   0, 120,   0, 116,   0,
  32,   0, 104,   0, 101,   0, 114,   0, 101,   0,  46,   0,  46,   0,  46,   0
]

 

See also

  1. ASCII Table

  2. ASCII Table in plain/text

  3. JavaScript - convert string to bytes array - Universal Approach

  4. JavaScript - convert bytes array to string - Universal Approach

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join