'How to read binary file byte by byte using javascript?

I need to read the binary file byte by byte using javascript.I had got below code in this site,but its not working.I think i have to add some extra src file as a reference to it.Please help me to do it.here the code...

var fs = require('fs');
var Buffer = require('buffer').Buffer;
var constants = require('constants');

fs.open("file.txt", 'r', function(status, fd) {
    if (status) {
        console.log(status.message);
        return;
    }
    var buffer = new Buffer(100);
    fs.read(fd, buffer, 0, 100, 0, function(err, num) {
        console.log(buffer.toString('utf-8', 0, num));
    });
}); 


Solution 1:[1]

You can use the following code:

var blob = file.slice(startingByte, endindByte);
reader.readAsBinaryString(blob);

Here's how it works:

  • file.slice will slice a file into bytes and save to a variable as binary. You can slice by giving the start byte and end byte.

  • reader.readAsBinaryString will print that byte as binary file. It doesn't matter how big the file is.

For more info, see this link.

Solution 2:[2]

import { readFile } from 'fs/promises';

// read the file into a buffer (https://nodejs.org/api/fs.html#fspromisesreadfilepath-options)
(await readFile('file.txt'))
  // (optional) read just a portion of the file
  .slice(startingByte, endingByte)
  // process each byte however you like
  .forEach((byte) => console.log(byte));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt
Solution 2 bmaupin