3

I have a function called ReadBinaryData() which I would like to create a Read Stream to read binary data and return the binary data back to the calling function via a callback. It seems you can do this w/ Node a few different ways and I have read conflicting info on how to do it. I think I should be using the Buffer object, but not really sure how. I have the following, but it does not seem to be working correctly. Any suggestions ?

function ReadBinaryData(successCallback){               
    var streamHandle = fs.createReadStream("PATH TO FILE",  {encoding: 'binary'});      
    var contentRead = '';       
   streamHandle.addListener('data', function(data) {            
        contentRead += data;                            
    });

   streamHandle.addListener('end', function(data) {                         
        successCallback(contentRead);       
    });     
};
1
  • when I log the output I dont get the binary data. I get garbled characters. How can I output the binary or verify that the output is indeed binary ? (excuse my lack of understanding of binary data) Commented Sep 15, 2011 at 17:11

1 Answer 1

1

I used the nodejs Buffer in the 5.x branch. I'd check out the docs there and read up. There are a lot of new methods in there that will help with your binary stream. Although, the binary option is being removed in future versions, so you might want to rethink what you're doing and why.

http://nodejs.org/docs/v0.5.6/api/buffers.html

Here is an example use of the buffer though, i'm using the 5.x branch for this code, there is a similar method that is like writeUInt32LE but for binary. There are also corresponding read methods. If you can't use the 5.x branch, you might be able to look at the nodejs javascript libs and see how their method is transforming the string to the format you want.

  var cur = this.network.ipInt;
  var bcast = this.broadcast.ipInt;
  var addresses = new Buffer((bcast-cur)*10);
  var offset = 0;
  while (cur < bcast){
    cur += 1;
    addresses.writeUInt32LE(cur,offset);
    offset+=10;
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.