Search code examples
javascriptutf-16

Javascript: create UTF-16 text file?


I have some string need to be a UTF-16 text file. For example:

var s = "aosjdfkzlzkdoaslckjznx";
var file = "data:text/plain;base64," + btoa(s);

This will result a UTF-8 encoding text file. How can I get a UTF-16 text file with string s?


Solution

  • You can use a legacy polyfill of the native TextEncoder API to transform a JavaScript string into an ArrayBuffer. As you'll see in that documentation, UTF16 with either endianness is was supported. Libraries that provide UTF-16 support in a Text-Encoder-compatible way will probably appear soon, if they haven't already. Let's assume that one such library exposes a constructor called ExtendedTextEncoder.

    Then you can easily create a Blob URL to allow users to download the file, without the inefficient base-64 conversion.

    Something like this:

    s = "aosjdfkzlzkdoaslckjznx"
    var encoder = new ExtendedTextEncoder("utf-16be")
    var blob = new Blob(encoder.encode(s), "text/plain")
    var url = URL.createObjectURL(blob)
    

    Now you can use url instead of your data: URL.