Node.jsで文字列をUnit8Arrayに変換する方法です。
const str = 'Hello こんにちは'
const encoder = new TextEncoder()
const encoded = encoder.encode(str)
console.log(encoded)
実行結果:
Uint8Array(21) [
72, 101, 108, 108, 111, 32,
227, 129, 147, 227, 130, 147,
227, 129, 171, 227, 129, 161,
227, 129, 175
]
簡単な説明
-
TextEncoder
のencode
メソッドに文字列を渡すと、Unit8Array
が返ってくる。 - UTF-8のみサポートしている。
-
TextEncoder
のインターフェイスはWHATWG Encoding Standard TextEncoder APIに準拠している。