将字节数组保存到文件节点JS

Anu*_*dey 1 file writefile node.js

我想将bytearray保存到节点js中的文件中,对于android我正在使用下面的代码示例.任何人都可以建议我采用类似的方法吗?

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();
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*and 11

Leonenko的回答引用/复制了正确的JavaScript文档,但事实证明,writeFile与Uint8Array不能很好地协作 - 它只是将字节写为数字:

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

要使它工作,必须将Uint8Array包装在Buffer中:

fs.writeFile('testfile',new Buffer(ui8a),...)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!这对我有用。我收到警告`DeprecationWarning:由于安全性和可用性问题,不建议使用Buffer()。请改用Buffer.alloc(),Buffer.allocUnsafe()或Buffer.from()方法。我所做的就是将new Buffer()转换为Buffer.from(),警告消失了。 (3认同)

Iva*_*nko 9

使用fs.writeFile将字符串或字节数组写入文件。

  • 文件文件<String> | <Buffer> | <Integer>名或文件描述符
  • 数据 <String> | <Buffer> | <Uint8Array>
  • 选项 <Object> | <String>
    • 编码<String> | <Null>默认 = 'utf8'
    • 模式<Integer>默认值 = 0o666
    • 标志<String>默认 = 'w'
    • 打回来 <Function>

将数据异步写入文件,如果文件已存在则替换该文件。数据可以是字符串或缓冲区。

如果数据是缓冲区,则忽略编码选项。它默认为“utf8”。

const fs = require('fs');

// Uint8Array
const data = new Uint8Array(Buffer.from('Hello Node.js'));
fs.writeFile('message.txt', data, callback);

// Buffer
fs.writeFile('message.txt', Buffer.from('Hello Node.js'), callback);

// string
fs.writeFile('message.txt', 'Hello Node.js', callback);

var callback = (err) => {
  if (err) throw err;
  console.log('It\'s saved!');
}
Run Code Online (Sandbox Code Playgroud)