How to save ArrayBuffer?

后端 未结 3 1874
北恋
北恋 2020-12-22 07:56

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 con

相关标签:
3条回答
  • 2020-12-22 08:23

    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.

    0 讨论(0)
  • 2020-12-22 08:28

    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 讨论(0)
  • 2020-12-22 08:32

    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));
    
    0 讨论(0)
提交回复
热议问题