How to write and read bits one by one in a file via NodeJS?

binary, buffer, machine-code, node.js, stream

Solution

Buffers operate at the byte level. Once you access a particular byte (e.g. `buff[0]`), it's just a normal javascript number, so you can you do whatever bit operations on that number (e.g. `buff[0] & 0x0F`).

There are convenience functions on Buffer objects that allow you to write different kinds of numbers too. For example: `buff.writeUInt32BE(5, 0)` will write a 32-bit unsigned integer 5 in big endian mode at position 0 in the Buffer. To read a 32-bit unsigned integer in big endian mode at position 0: `buff.readUInt32BE(0)`.

Problem

I want to create a binary file using `0` and `1` bit values and then I want to read them one by one. How can I do this? For writing I tried: ``` var out = require("fs").createWriteStream("./out"); out.write(new Buffer("0")); // this writes "0" as string out.write(new Buffer(["0"])); // this creates something strange, // but I'm not sure it's the needed thing ``` After the file exists, I want to iterate all bits from that file: ``` require("fs").readFile("./out", function (err, buff) { // how to access here `0` and `1` values? }); ``` What's the proper way for doing this?

Original source