最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to save ArrayBuffer? - Stack Overflow

programmeradmin1浏览0评论

How to save an ArrayBuffer in json file? I use electron-config for this, but in config.json I found "{}". I try convert (code) ArrayBuffer to string, but then I can't convert string to 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;
}

How to save an ArrayBuffer in json file? I use electron-config for this, but in config.json I found "{}". I try convert (code) ArrayBuffer to string, but then I can't convert string to 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;
}
Share Improve this question edited Dec 26, 2016 at 18:26 mscdex 107k15 gold badges201 silver badges159 bronze badges asked Dec 26, 2016 at 8:31 Aynur SibagatullinAynur Sibagatullin 1531 gold badge1 silver badge11 bronze badges 4
  • 1 Why do you need to store binary data in JSON? Are you sending an HTTP request to a server? If so, you'd be better off with something that is binary-friendly, such as multipart/form-data instead of JSON. – mscdex Commented Dec 26, 2016 at 8:43
  • @mscdex Not necessarily in JSON format. I just want to save ArrayBuffer on PC. – Aynur Sibagatullin Commented Dec 26, 2016 at 8:46
  • You mean save it to a file on the local puter's disk or do you mean save it in the browser, like via LocalStorage (which does not support binary data natively btw)? – mscdex Commented Dec 26, 2016 at 10:54
  • @mscdex I mean save it on the local puter's disk (Electron app). – Aynur Sibagatullin Commented Dec 26, 2016 at 10:59
Add a ment  | 

3 Answers 3

Reset to default 5

For saving to disk, you should be able to use the normal node APIs for writing something to disk. For example:

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

There are no ArrayBuffers in the JSON format (only strings, numbers, booleans, null, objects and arrays) so if you want to save an ArrayBuffer in JSON then you'll have to represent it in one of those types (probably a string or an array of numbers).

Then when you read the JSON you will have to convert it back into an ArrayBuffer, reversing the transformation that you did before.

Working Snippet Node 14.xx+

Create a output directory

  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")

Save file function

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)
          }
      });
};
发布评论

评论列表(0)

  1. 暂无评论