Node.js의 문자열과 바이트 배열 (Uint8Array, Buffer)

  • 일반적으로 영어 알파벳, 숫자, 특수 기호는 1byte, 한글은 2byte의 크기를 가진다. (utf-8)
  • ES2018부터는 TextEncoder()를 사용할 수 있다.

문자열을 Uint8Array으로 변환하기

const utf8Encode = new TextEncoder();
const encode = utf8Encode.encode('aaaabbbbccccdddd');

console.log(encode);
/*
 Uint8Array(16) [
   97,  97,  97,  97, 98, 98,
   98,  98,  99,  99, 99, 99,
   100, 100, 100, 100 ]
*/

// 다시 문자열로
const utf8Decode = new TextDecoder();
console.log(utf8Decode.decode(encode));
// testtest
  • 다시 Uint8Array를 문자열로 변환할 때에는 TextDecoder를 사용한다.

문자열을 Buffer로 변환하기

const stringToBuffer = (str) => {
  const buffer = Buffer.from(str, 'utf8');
  return buffer;
};

const buffer = stringToBuffer('aaaabbbbccccddddeeeeffff');
console.log(buffer);
// <Buffer 61 61 61 61 62 62 62 62 63 63 63 63 64 64 64 64 65 65 65 65 66 66 66 66>

// 다시 문자열로
console.log(key3.toString('utf8')); // aaaabbbbccccddddeeeeffff
  • 문자열로 되돌아올 때 내장 메서드 toString을 사용한다.

문자열의 bytes 길이 확인하기

// Uint8Array
const utf8Encode = new TextEncoder();
const utf8Encode = utf8Encode.encode('testtest');
console.log(utf8Encode.length); // 8

// Buffer
const bufferLen = Buffer.byteLength("testtest", 'utf8');
const buffer = Buffer.from("testtest", 'utf8');
console.log(bufferLen, buffer.length); // 8 8


// Blob
const blob = new Blob(["testtest"]);
console.log(blob.size); // 8
  • 브라우저 환경에서 Buffer나 TextEncoder를 사용하려면, polyfill 설정이 필요할 수 있다.
  • polyfill 설정 없이 브라우저 환경에서 bytes 데이터를 사용하고자 한다면, blob을 이용할 수 있다. (Blob은 노드 환경에서는 사용할 수 없다)

 

참고 자료 : https://stackoverflow.com/questions/6226189/how-to-convert-a-string-to-bytearray

 

How to convert a String to Bytearray

How can I convert a string in bytearray using JavaScript. Output should be equivalent of the below C# code. UnicodeEncoding encoding = new UnicodeEncoding(); byte[] bytes = encoding.GetBytes(AnySt...

stackoverflow.com

https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder

 

TextEncoder - Web APIs | MDN

The TextEncoder interface takes a stream of code points as input and emits a stream of UTF-8 bytes.

developer.mozilla.org

https://stackoverflow.com/questions/5515869/string-length-in-bytes-in-javascript

 

String length in bytes in JavaScript

In my JavaScript code I need to compose a message to server in this format: <size in bytes>CRLF <data>CRLF Example: 3 foo The data may contain unicode characters. I need to send the...

stackoverflow.com