Trajanson Trajanson - 7 months ago 16
Javascript Question

How to Write Binary (not UTF-8) to File

I have an array of numbers, which I would like to write to a file using Node.JS.

If I have a number: 256

The file should contain the binary:

`00000001 00000000`

And not:

`00000010 00000101 00000110`

The reason for asking this question is that I have read that the binary string format for buffers is being deprecated1.


The Buffer class can handle arrays of numbers directly:

// Old style
var buffer = new Buffer([ 150 ]);

// New style
var buffer = Buffer.from([ 150 ]);

// Write the buffer to a file.
// Using `fs.writeFileSync()` just as an example here.
require('fs').writeFileSync('output.bin', buffer);

If you're dealing with larger numbers (not bytes), you need to use a typed array.

For instance, using 16-bit unsigned values:

var array    = [ 5000, 4000 ];
var u16array = Uint16Array.from(array);
var buffer   = new Buffer(u16array.buffer);

require('fs').writeFileSync('output.bin', buffer);