简体   繁体   English

从NodeJS返回二进制数据

[英]Returning binary data from NodeJS

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. 我有一个名为ReadBinaryData()的函数,我想创建一个读取流来读取二进制数据并通过回调将二进制数据返回给调用函数。 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. 我想我应该使用Buffer对象,但不确定如何。 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);       
    });     
};

I used the nodejs Buffer in the 5.x branch. 我在5.x分支中使用了nodejs Buffer。 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 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. 下面是缓冲区的一个示例用法,我使用的是5.x分支代码,有一个类似于writeUInt32LE的方法,但是对于二进制文件。 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. 如果你不能使用5.x分支,你可以查看nodejs javascript libs并看看他们的方法如何将字符串转换为你想要的格式。

  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;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM