如何将ArrayBuffer保存到json文件中?我使用了电子配置,但在config.json中我找到了"{}“。我尝试将(code) ArrayBuffer转换为string,但是无法将string转换为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;
}发布于 2016-12-27 02:30:39
为了保存到磁盘,您应该能够使用普通的节点API将某些内容写入磁盘。例如:
require('fs').writeFileSync('/path/to/saved/file', Buffer.from(myArrayBuffer));发布于 2016-12-26 18:35:26
没有JSON格式的ArrayBuffers (只有字符串、数字、布尔值、null、对象和数组),所以如果您想要以JSON格式保存ArrayBuffer,那么必须用这些类型中的一种(可能是字符串或数字数组)来表示它。
然后,当您读取JSON时,您必须将其转换回ArrayBuffer,这与您之前所做的转换相反。
发布于 2020-10-05 23:14:02
工作代码段节点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)
}
});
};https://stackoverflow.com/questions/41328483
复制相似问题