Save byte array to file node JS

Anuj J Pandey picture Anuj J Pandey · Feb 2, 2017 · Viewed 20.8k times · Source

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();
            }

Answer

John Tang Boyland picture John Tang Boyland · Oct 30, 2017

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),...)