是否有一种普遍接受的技术可以有效地将JavaScript字符串转换为arraybuffer,反之亦然?具体来说,我希望能够将ArrayBuffer的内容写入localStorage,然后再将其读回来。


当前回答

Yes:

const encstr = (`TextEncoder` in window) ? new TextEncoder().encode(str) : Uint8Array.from(str, c => c.codePointAt(0));

其他回答

与这里的解决方案不同,我需要从UTF-8数据转换到UTF-8数据。为此,我使用(un)escape/(en)decodeURIComponent技巧编写了以下两个函数。它们非常浪费内存,分配的长度是编码后utf8-string的9倍,尽管这些应该由gc恢复。只是不要在100mb的文本中使用它们。

function utf8AbFromStr(str) {
    var strUtf8 = unescape(encodeURIComponent(str));
    var ab = new Uint8Array(strUtf8.length);
    for (var i = 0; i < strUtf8.length; i++) {
        ab[i] = strUtf8.charCodeAt(i);
    }
    return ab;
}

function strFromUtf8Ab(ab) {
    return decodeURIComponent(escape(String.fromCharCode.apply(null, ab)));
}

检查它是否工作:

strFromUtf8Ab(utf8AbFromStr('latinкирилицаαβγδεζηあいうえお'))
-> "latinкирилицаαβγδεζηあいうえお"

2016年更新——五年过去了,现在规范中有了新的方法(参见下面的支持),可以使用适当的编码在字符串和类型化数组之间进行转换。

TextEncoder

TextEncoder表示:

TextEncoder接口表示特定方法的编码器, 这是一种特定的字符编码,如utf-8, iso-8859-2, koi8, Cp1261, gbk,…编码器以码点流作为输入 发出一个字节流。

自写上篇以来的变动注:(同上)

注意:Firefox, Chrome和Opera曾经支持编码 utf-8以外的类型(如utf-16、iso-8859-2、koi8、cp1261和 gbk)。Firefox 48[…]], Chrome 54[…]Opera 41,没有 为了匹配,除了utf-8,还有其他编码类型可用 规范。*

*)更新规格(W3)和这里(whatwg)。

在创建TextEncoder实例后,它将接受一个字符串并使用给定的编码参数对其进行编码:

如果(!("TextEncoder"在窗口)) alert(“对不起,这个浏览器不支持TextEncoder…”); var enc = new TextEncoder();// always utf-8 console.log(内附。encode("这是一个转换为Uint8Array的字符串"));

当然,如果需要的话,你可以在结果的Uint8Array上使用.buffer参数来将底层的ArrayBuffer转换为不同的视图。

只需确保字符串中的字符符合编码模式,例如,如果在示例中使用UTF-8范围之外的字符,它们将被编码为两个字节而不是一个字节。

一般情况下,你可以使用UTF-16编码来处理localStorage之类的东西。

TextDecoder

同样,相反的进程使用TextDecoder:

TextDecoder接口表示特定方法的解码器, 这是一种特定的字符编码,如utf-8, iso-8859-2, koi8, Cp1261, gbk,…解码器接受字节流作为输入并发出 代码点流。

所有可用的解码类型都可以在这里找到。

如果(!(“TextDecoder”在窗口)) alert(“抱歉,这个浏览器不支持TextDecoder…”); var enc = new TextDecoder("utf-8"); var arr = new Uint8Array([84,104,105,115,32,105,115,32,97,32,85,105,110,116, 56、65114114、97121、99111110118101114116, 101100, 32116111, 97, 32115116114105110103]); console.log (enc.decode (arr));

MDN StringView库

另一种选择是使用StringView库(许可为lgpl-3.0),其目标是:

to create a C-like interface for strings (i.e., an array of character codes — an ArrayBufferView in JavaScript) based upon the JavaScript ArrayBuffer interface to create a highly extensible library that anyone can extend by adding methods to the object StringView.prototype to create a collection of methods for such string-like objects (since now: stringViews) which work strictly on arrays of numbers rather than on creating new immutable JavaScript strings to work with Unicode encodings other than JavaScript's default UTF-16 DOMStrings

给予更多的灵活性。然而,它需要我们链接到或嵌入这个库,而TextEncoder/TextDecoder是内置在现代浏览器中。

支持

截至2018年7月:

TextEncoder(实验性,在标准轨道上)

 Chrome    | Edge      | Firefox   | IE        | Opera     | Safari
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |    19°    |     -     |     25    |     -

 Chrome/A  | Edge/mob  | Firefox/A | Opera/A   |Safari/iOS | Webview/A
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |    19°    |     ?     |     -     |     38

°) 18: Firefox 18 implemented an earlier and slightly different version
of the specification.

WEB WORKER SUPPORT:

Experimental, On Standard Track

 Chrome    | Edge      | Firefox   | IE        | Opera     | Safari
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |     20    |     -     |     25    |     -

 Chrome/A  | Edge/mob  | Firefox/A | Opera/A   |Safari/iOS | Webview/A
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |     20    |     ?     |     -     |     38

Data from MDN - `npm i -g mdncomp` by epistemex
var decoder = new TextDecoder ();
var string = decoder.decode (arrayBuffer);

参见https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder/decode

atob()返回的“本机”二进制字符串是一个每个字符1字节的数组。

所以我们不应该在一个字符中存储2个字节。

var arrayBufferToString = function(buffer) {
  return String.fromCharCode.apply(null, new Uint8Array(buffer));
}

var stringToArrayBuffer = function(str) {
  return (new Uint8Array([].map.call(str,function(x){return x.charCodeAt(0)}))).buffer;
}

ArrayBuffer -> Buffer ->字符集(Base64)

将ArrayBuffer改为Buffer,然后改为String。

Buffer.from(arrBuffer).toString("base64");