상세 컨텐츠

본문 제목

TextDecoder()

JavaScript

by 폴리프레임 2024. 6. 14. 19:56

본문

반응형

TextDecoder 클래스는 JavaScript에서 ArrayBuffer나 TypedArray와 같은 바이너리 데이터를 텍스트로 변환하는 데 사용됩니다. 이 클래스는 다양한 문자인코딩을 지원하며, 바이너리 데이터를 특정 문자 인코딩에 따라 문자열로 디코딩할 수 있게 해줍니다( UTF-8, UTF-16, ISO-8859-1 등) .   스트림 디코딩  즉 데이터가 점진적으로 들어올 때 점진적으로 디코딩할 수 있습니다.

생성자

  • new TextDecoder([label[, options]]): 새로운 TextDecoder 인스턴스를 생성합니다.
    • label (선택): 사용할 문자 인코딩을 나타내는 문자열 (기본값은 'utf-8').
    • options (선택): 디코딩 옵션을 포함하는 객체. fatal과 ignoreBOM 옵션을 설정할 수 있습니다.

주요 메서드

  • decode(value[, options]): 지정된 input (ArrayBuffer나 TypedArray)을 문자열로 디코딩합니다.
    • value: 디코딩할 데이터. 통상 const  { done, value } = await reader.read();에서 value 값을 받는다.
    • options: 스트림 옵션을 포함하는 객체. stream 옵션을 설정할 수 있습니다.
<!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>

'JavaScript' 카테고리의 다른 글

.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

관련글 더보기