Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read binary files byte by byte in Node.js

What is the best way to read part of a binary file in Node.js?

I am looking to either access specific bytes in the "header" (less than the first 100 bytes) or read the file byte by byte.

like image 291
Alec Gorge Avatar asked Apr 26 '11 00:04

Alec Gorge


People also ask

How do you read bytes in binary?

You can open the file using open() method by passing b parameter to open it in binary mode and read the file bytes. open('filename', "rb") opens the binary file in read mode.

How do I view binary files?

To open the Binary Editor on an existing file, go to menu File > Open > File, select the file you want to edit, then select the drop arrow next to the Open button, and choose Open With > Binary Editor.


1 Answers

Here is an example of fs.read()-ing the first 100 bytes from a file descriptor returned by fs.open():

var fs = require('fs');  fs.open('file.txt', 'r', function(status, fd) {     if (status) {         console.log(status.message);         return;     }     var buffer = Buffer.alloc(100);     fs.read(fd, buffer, 0, 100, 0, function(err, num) {         console.log(buffer.toString('utf8', 0, num));     }); }); 
like image 188
samplebias Avatar answered Sep 21 '22 13:09

samplebias