Javascript:创建UTF-16文本文件?

Wil*_*niz 1 javascript utf-16

我有一些字符串需要是一个UTF-16文本文件.例如:

var s = "aosjdfkzlzkdoaslckjznx";
var file = "data:text/plain;base64," + btoa(s);
Run Code Online (Sandbox Code Playgroud)

这将导致UTF-8编码文本文件.如何获得带字符串的UTF-16文本文件s

ski*_*ulk 9

相关:Javascript到csv导出编码问题

这应该这样做:

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-16BE;'});
  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();
  }
}
Run Code Online (Sandbox Code Playgroud)
<button id="download">Download</button>
Run Code Online (Sandbox Code Playgroud)