Trajanson
Trajanson

Reputation: 441

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.

Upvotes: 0

Views: 180

Answers (2)

tangxinfa
tangxinfa

Reputation: 1510

Please take a look at Buffer's documention: https://nodejs.org/api/buffer.html

Buffer support read/write binary numbers:

buf.readDoubleBE(offset[, noAssert])
buf.readDoubleLE(offset[, noAssert])
buf.readFloatBE(offset[, noAssert])
buf.readFloatLE(offset[, noAssert])
buf.readInt8(offset[, noAssert])
buf.readInt16BE(offset[, noAssert])
buf.readInt16LE(offset[, noAssert])
buf.readInt32BE(offset[, noAssert])
buf.readInt32LE(offset[, noAssert])
buf.readIntBE(offset, byteLength[, noAssert])
buf.readIntLE(offset, byteLength[, noAssert])
buf.readUInt8(offset[, noAssert])
buf.readUInt16BE(offset[, noAssert])
buf.readUInt16LE(offset[, noAssert])
buf.readUInt32BE(offset[, noAssert])
buf.readUInt32LE(offset[, noAssert])
buf.readUIntBE(offset, byteLength[, noAssert])
buf.readUIntLE(offset, byteLength[, noAssert])

Upvotes: 0

robertklep
robertklep

Reputation: 203494

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

Upvotes: 1

Related Questions