8

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));
    });
}); 
2
  • Do you need to read it byte by byte or do you need to process its contents byte by byte? Commented Apr 4, 2013 at 10:27
  • 2
    You would need Node.js for this, don't you? Commented Mar 20, 2014 at 12:43

3 Answers 3

9

You can read the file synchronously, byte by byte:

fs.open('file.txt', 'r', function(err, fd) {
  if (err)
    throw err;
  var buffer = Buffer.alloc(1);
  while (true)
  {   
    var num = fs.readSync(fd, buffer, 0, 1, null);
    if (num === 0)
      break;
    console.log('byte read', buffer[0]);
  }
});
Sign up to request clarification or add additional context in comments.

3 Comments

It's better to use var buffer = Buffer.alloc(1);
@Saman sure, but that didn't exist 6 years ago when the answer was posted. Also, I would suggest using const.
Sure, I've put it for new visitors like myself. thanks.
2

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.

1 Comment

This is an interesting answer, but it seems to use the web FileReader API, which isn't available in Node.js and so unfortunately isn't applicable to the specific question.
0
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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.