From the docs:
readFileSync
If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.
Buffer
Instances of the Buffer class are similar to arrays of integers but correspond to fixed-sized, raw memory allocations outside the V8 heap. Now that TypedArray has been added in ES6, the Buffer class implements the Uint8Array API in a manner that is more optimized and suitable for Node.js' use cases.
So readFileSync is creating a Buffer object, which makes use of Uint8Array
(Array of array of 8 unsigned integers) (You can look at the API on MDN docs). Thus Uint8Array.isPrototypeOf(Buffer) === true
or in English, the Buffer object's prototype is the Uint8Array's prototype. So Buffer incorporates all of Uint8's functionality but masks some of it with its own.
So we could create a new Uint8Array from a string (ascii encoding because the ascii table is easy to follow) with Buffer's convenient method:
const buff = Buffer.from('test', 'ascii');
Uint8Array.from() without the Buffer wrapper asks specifically for an iterable object of numbers e.g. [116, 101, 115, 116]
('test' in ascii decimal representation). But Buffer lets us use a string directly.
Buffer is an iterable ES6's iteration syntax for (let b of buff)
can be used, as can Array.from(buff).forEach()
or Array.prototype.forEach.call(buff)
to iterate through each value. You could then use this iteration to convert each individual numeric representation of your original characters to a binary string.
I won't go through this exactly, but you can use Number.toString(2) to transform the number to a Base 2 (binary) number, then pad the digits to the left with 0.