如何保存ArrayBuffer?

时间:2016-12-26 08:31:46

标签: javascript json node.js electron

如何在json文件中保存ArrayBuffer?我使用electron-config,但是在config.json中我找到了“{}”。我尝试将(code)ArrayBuffer转换为字符串,但后来我无法将字符串转换为ArrayBuffer。

put: function(key, value) {
    //value = { prop1: <ArrayBuffer>, prop2: <ArrayBuffer> }
    if (key === undefined || value === undefined || key === null || value === null)
        return;
    var prop1Str,prop2Str;
    prop1Str = this.ab2str(value.prop1);
    prop2Str = this.ab2str(value.prop2);
    var chValue = {prop1:prop1Str, prop2:prop2Str};
    config.set(key,chValue);
    console.log(value.prop1 === this.str2ab(config.get(key).prop1)); //===> FALSE
},
ab2str: function(buf) {
    return String.fromCharCode.apply(null, new Uint8Array(buf));
},
str2ab: function(str) {
    var buf = new ArrayBuffer(str.length);
    var bufView = new Uint16Array(buf);
    for (var i=0, strLen=str.length; i < strLen; i++) {
        bufView[i] = str.charCodeAt(i);
    }
    return buf;
}

3 个答案:

答案 0 :(得分:2)

JSON格式中没有ArrayBuffers(只有字符串,数字,布尔值,null,对象和数组)所以如果要在JSON中保存ArrayBuffer,那么你必须在其中一种类型(可能是字符串或数组)。

然后,当您阅读JSON时,您必须将其转换回ArrayBuffer,从而扭转您之前所做的转换。

答案 1 :(得分:1)

要保存到磁盘,您应该能够使用普通节点API将内容写入磁盘。例如:

require('fs').writeFileSync('/path/to/saved/file', Buffer.from(myArrayBuffer));

答案 2 :(得分:0)

工作代码段节点14.xx +

创建输出目录

  let rootDir = process.cwd()
  console.log("Current Directory"+ rootDir)

  let outDir = './out/';
  console.log("Out Directory"+ outDir)

  if (!fs.existsSync(outDir)){
      fs.mkdirSync(outDir);
  }else{
      console.log("Directory already exist");
  }
   
  // Save the raw file for each asset to the current working directory
  saveArrayAsFile(arrayBuffer,  outDir+ "fileName"+ new Date().getTime()+".png")

保存文件功能

const saveArrayAsFile =  (arrayBuffer, filePath)=> {
      fs.writeFile(filePath, Buffer.from(arrayBuffer), 'binary',  (err)=> {
          if (err) {
              console.log("There was an error writing the image")
          }
          else {
              console.log("Written File :" + filePath)
          }
      });
};