Save byte array to file node JS
Asked Answered
S

3

13

I want to save bytearray to a file in node js, for android I'm using the below code sample, can anyone 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();
            }
Stefan answered 2/2, 2017 at 9:59 Comment(0)
O
20

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'.

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!');
}
Oestrogen answered 2/2, 2017 at 15:57 Comment(0)
G
23

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),...)
Gatecrasher answered 30/10, 2017 at 14:46 Comment(3)
thank you! This worked for me. I got the warning DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead. All I did was convert new Buffer( to Buffer.from( and the warning is gone.Zeebrugge
What does "doesn't play nicely" mean ? What may go wrong ? Uint8Array works fine for me.Durance
The behavior seems to have changed since I wrote my answer in an older version of nodeJSGatecrasher
O
20

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'.

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!');
}
Oestrogen answered 2/2, 2017 at 15:57 Comment(0)
B
0

Working Snippet Node 14.xx+ Write Buffer to File

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 Array Buffer into filePath

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)
          }
      });
};
Bambara answered 5/10, 2020 at 15:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.