TextDecoder 클래스는 JavaScript에서 ArrayBuffer나 TypedArray와 같은 바이너리 데이터를 텍스트로 변환하는 데 사용됩니다. 이 클래스는 다양한 문자인코딩을 지원하며, 바이너리 데이터를 특정 문자 인코딩에 따라 문자열로 디코딩할 수 있게 해줍니다( UTF-8, UTF-16, ISO-8859-1 등) . 스트림 디코딩 즉 데이터가 점진적으로 들어올 때 점진적으로 디코딩할 수 있습니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TextDecoder Example</title>
</head>
<body>
<script>
// UTF-8로 인코딩된 텍스트 데이터
const utf8Array = new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);
// TextDecoder 인스턴스 생성
const decoder = new TextDecoder('utf-8');
// 디코딩
const decodedText = decoder.decode(utf8Array);
// 결과 출력
console.log(decodedText); // "Hello World"
</script>
</body>
</html>
스트림 디코딩 예제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TextDecoder Streaming Example</title>
</head>
<body>
<script>
// 큰 바이너리 데이터가 여러 조각으로 들어오는 경우를 가정
const chunks = [
new Uint8Array([72, 101, 108, 108]),
new Uint8Array([111, 32, 87]),
new Uint8Array([111, 114, 108, 100])
];
const decoder = new TextDecoder('utf-8');
let decodedText = '';
// 스트림으로 각 조각을 디코딩
for (let chunk of chunks) {
decodedText += decoder.decode(chunk, { stream: true });
}
// 마지막 조각 디코딩 (스트림 종료)
decodedText += decoder.decode(); // 스트림이 끝났음을 알림
console.log(decodedText); // "Hello World"
</script>
</body>
</html>
.at() (0) | 2024.06.18 |
---|---|
scrollHeight, scrollTop (0) | 2024.06.18 |
ArrayBuffer, TypedArray, Int8Array, Unit8Array (2) | 2024.06.14 |
FileReader() (1) | 2024.06.14 |
get() set() - class (1) | 2024.06.14 |