এনকোডিং এপিআই সহ স্ট্রিং রূপান্তর থেকে সহজ অ্যারেবাফার

দুই বছর আগে, রেনাটো মাঙ্গিনি কাঁচা অ্যারেবাফার এবং সেই ডেটার সংশ্লিষ্ট স্ট্রিং উপস্থাপনার মধ্যে রূপান্তর করার একটি পদ্ধতি বর্ণনা করেছিলেন। পোস্টের শেষে, রেনাটো উল্লেখ করেছেন যে রূপান্তরটি পরিচালনা করার জন্য একটি অফিসিয়াল প্রমিত API খসড়া তৈরির প্রক্রিয়াধীন ছিল। স্পেসিফিকেশন এখন পরিপক্ক হয়েছে, এবং Firefox এবং Google Chrome উভয়ই TextDecoder এবং TextEncoder ইন্টারফেসের জন্য স্থানীয় সমর্থন যোগ করেছে।

এই লাইভ নমুনা দ্বারা প্রদর্শিত হিসাবে, নীচে উদ্ধৃত করা হয়েছে, এনকোডিং এপিআই কাঁচা বাইট এবং নেটিভ জাভাস্ক্রিপ্ট স্ট্রিংগুলির মধ্যে অনুবাদ করা সহজ করে তোলে, আপনাকে যে অনেকগুলি স্ট্যান্ডার্ড এনকোডিংয়ের সাথে কাজ করতে হবে তা নির্বিশেষে।

<pre id="results"></pre>

<script>
    if ('TextDecoder' in window) {
    // The local files to be fetched, mapped to the encoding that they're using.
    var filesToEncoding = {
        'utf8.bin': 'utf-8',
        'utf16le.bin': 'utf-16le',
        'macintosh.bin': 'macintosh'
    };

    Object.keys(filesToEncoding).forEach(function(file) {
        fetchAndDecode(file, filesToEncoding[file]);
    });
    } else {
    document.querySelector('#results').textContent = 'Your browser does not support the Encoding API.'
    }

    // Use XHR to fetch `file` and interpret its contents as being encoded with `encoding`.
    function fetchAndDecode(file, encoding) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file);
    // Using 'arraybuffer' as the responseType ensures that the raw data is returned,
    // rather than letting XMLHttpRequest decode the data first.
    xhr.responseType = 'arraybuffer';
    xhr.onload = function() {
        if (this.status == 200) {
        // The decode() method takes a DataView as a parameter, which is a wrapper on top of the ArrayBuffer.
        var dataView = new DataView(this.response);
        // The TextDecoder interface is documented at http://encoding.spec.whatwg.org/#interface-textdecoder
        var decoder = new TextDecoder(encoding);
        var decodedString = decoder.decode(dataView);
        // Add the decoded file's text to the <pre> element on the page.
        document.querySelector('#results').textContent += decodedString + '\n';
        } else {
        console.error('Error while requesting', file, this);
        }
    };
    xhr.send();
    }
</script>

বর্তমান ব্রাউজারে প্রয়োজনীয় TextDecoder ইন্টারফেস উপলব্ধ কিনা তা নির্ধারণ করতে উপরের নমুনা বৈশিষ্ট্য সনাক্তকরণ ব্যবহার করে এবং এটি না থাকলে একটি ত্রুটি বার্তা প্রদর্শন করে। একটি বাস্তব অ্যাপ্লিকেশনে, স্থানীয় সমর্থন উপলব্ধ না হলে আপনি সাধারণত একটি বিকল্প বাস্তবায়নে ফিরে যেতে চান। সৌভাগ্যবশত, রেনাটো তার মূল নিবন্ধে যে টেক্সট-এনকোডিং লাইব্রেরির কথা উল্লেখ করেছেন তা এখনও একটি ভাল পছন্দ। লাইব্রেরি তাদের সমর্থন করে এমন ব্রাউজারগুলিতে নেটিভ পদ্ধতিগুলি ব্যবহার করে এবং এখনও সমর্থন যোগ করেনি এমন ব্রাউজারগুলিতে এনকোডিং API-এর জন্য পলিফিল অফার করে৷

আপডেট, সেপ্টেম্বর 2014 : বর্তমান ব্রাউজারে এনকোডিং API উপলব্ধ কিনা তা পরীক্ষা করে দেখাতে নমুনাটি সংশোধন করা হয়েছে।