Save byte array to file node JS

可紊 提交于 2019-12-23 02:42:36

问题


I want to save bytearray to a file in node js, for android I'm using the below code sample. Can any once suggest me the similar approach?

File file = new File(root, System.currentTimeMillis() + ".jpg");
if (file.exists())
    file.delete();
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(file);
    fos.write(bytesarray);
    fos.close();
    return file;
}
catch (FileNotFoundException e) {
    e.printStackTrace();
}
catch (IOException e) {
    e.printStackTrace();
}

回答1:


Use fs.writeFile to write string or byte array into a file.

  • file <String> | <Buffer> | <Integer> filename or file descriptor
  • data <String> | <Buffer> | <Uint8Array>
  • options <Object> | <String>
    • encoding <String> | <Null> default = 'utf8'
    • mode <Integer> default = 0o666
    • flag <String> default = 'w'
    • callback <Function>

Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.

The encoding option is ignored if data is a buffer. It defaults to 'utf8'.

fs.writeFile('message.txt', 'Hello Node.js', (err) => {
  if (err) throw err;
  console.log('It\'s saved!');
});



回答2:


The answer by Leonenko cites/copies the correct JavaScript documentation, but it turns out that writeFile doesn't play nicely with a Uint8Array -- it simply writes the bytes out as numbers:

"84,104,101,32,102,105,114,115,..."

To get it to work, one has to wrap the Uint8Array in a Buffer:

fs.writeFile('testfile',new Buffer(ui8a),...)


来源:https://stackoverflow.com/questions/41999106/save-byte-array-to-file-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!