Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 696
Wilson Luniz Avatar asked Nov 16 '25 05:11

Wilson Luniz


2 Answers

Related: Javascript to csv export encoding issue

This should do it:

document.getElementById('download').addEventListener('click', function(){

	downloadUtf16('Hello, World', 'myFile.csv')
});

function downloadUtf16(str, filename) {

	// ref: https://stackoverflow.com/q/6226189
	var charCode, byteArray = [];

	// BE BOM
  byteArray.push(254, 255);

	// LE BOM
  // byteArray.push(255, 254);

  for (var i = 0; i < str.length; ++i) {
  
    charCode = str.charCodeAt(i);
    
    // BE Bytes
    byteArray.push((charCode & 0xFF00) >>> 8);
    byteArray.push(charCode & 0xFF);
    
    // LE Bytes
    // byteArray.push(charCode & 0xff);
    // byteArray.push(charCode / 256 >>> 0);
  }
  
  var blob = new Blob([new Uint8Array(byteArray)], {type:'text/plain;charset=UTF-8;'});
  var blobUrl = URL.createObjectURL(blob);
  
	// ref: https://stackoverflow.com/a/18197511
  var link = document.createElement('a');
  link.href = blobUrl;
  link.download = filename;

  if (document.createEvent) {
    var event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true);
    link.dispatchEvent(event);
  } else {
    link.click();
  }
}
<button id="download">Download</button>
like image 183
skibulk Avatar answered Nov 18 '25 20:11

skibulk


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.

like image 37
Touffy Avatar answered Nov 18 '25 19:11

Touffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!