Save Text as a UTF-16LE Encoded File

by skibulk

HTML

<button id="download">Download</button>

JavaScript

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

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

function downloadUtf16(str, filename) {

	// ref: http://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-16LE;'});
  var blobUrl = URL.createObjectURL(blob);
  
	// ref: http://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();
  }
}