EN
                                
                            
                        JavaScript - convert string to bytes array under Node.js
                                    9
                                    points
                                
                                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
- 
	
JavaScript - convert string to bytes array - Universal Approach
 - 
	
JavaScript - convert bytes array to string - Universal Approach