从 NodeJS 返回二进制数据
我有一个名为 ReadBinaryData() 的函数,我想创建一个读取流来读取二进制数据并通过回调将二进制数据返回到调用函数。看来你可以通过几种不同的方式使用 Node 来做到这一点,我已经阅读了有关如何做到这一点的相互冲突的信息。我认为我应该使用 Buffer 对象,但不太确定如何使用。我有以下内容,但它似乎无法正常工作。有什么建议吗?
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 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);
});
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在5.x分支中使用了nodejs Buffer。我会查看那里的文档并阅读。其中有很多新方法可以帮助您处理二进制流。不过,二进制选项将在未来的版本中被删除,因此您可能需要重新考虑您正在做什么以及为什么。
http://nodejs.org/docs/v0.5.6/api/buffers.html
这里是一个缓冲区的使用示例,我在这段代码中使用 5.x 分支,有一个类似的方法,类似于 writeUInt32LE,但适用于二进制。也有相应的读取方法。如果您无法使用 5.x 分支,您也许可以查看 nodejs javascript 库并了解它们的方法如何将字符串转换为您想要的格式。
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.