在node.js中读取二进制数据 [英] Reading binary data in node.js

查看:568
本文介绍了在node.js中读取二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读取node.js中的二进制数据时遇到问题.这就是我要做的:

I'm having problems reading binary data in node.js. This is what I do:

$ cat test.js 
var fs = require('fs'),
    binary = fs.readFileSync('./binary', 'binary').toString('binary');
process.stdout.write(binary.substring(0, 48));
$ xxd binary
00000000: 7f45 4c46 0201 0100 0000 0000 0000 0000  .ELF............
00000010: 0300 3e00 0100 0000 0008 0000 0000 0000  ..>.............
00000020: 4000 0000 0000 0000 10a0 0000 0000 0000  @...............
$ node test.js | xxd
00000000: 7f45 4c46 0201 0100 0000 0000 0000 0000  .ELF............
00000010: 0300 3e00 0100 0000 0008 0000 0000 0000  ..>.............
00000020: 4000 0000 0000 0000 10c2 a000 0000 0000  @...............
00000030: 00                                       .
$

请注意,使用节点读取时,如何在索引0x29处插入0xc2字节.这是为什么?我已经说过对readFileSynctoString都进行了二进制编码. 我也尝试过ascii,但结果却不同,同样错误.

Notice how a 0xc2 byte is inserted at index 0x29 when reading with node. Why is that? I've stated binary encoding both to readFileSync and toString. I've also tried ascii but then I get a different and equally wrong result.

推荐答案

'binary'编码是'latin1'的别名,在读取非字符数据时,您显然不希望使用它.

The 'binary' encoding is an alias for 'latin1', which you clearly don't want when reading non-character data.

如果您想要原始数据,完全不要指定编码(或供应null)*.您将得到一个 Buffer 而不是一个字符串,然后您会想要直接使用而不是在其上使用toString.

If you want the raw data, don't specify an encoding at all (or supply null)*. You'll get a Buffer instead of a string, which you'd then want to use directly rather than using toString on it.

*(某些API [例如fs.watch]也接受'buffer',但它不在 readFileSync的编码列表没有说明.[感谢 Patrick 提供列表链接.])

* (Some APIs [like fs.watch] also accept 'buffer', but it's not on the list of encodings and readFileSync doesn't say it does. [Thanks Patrick for providing the list link.])

这篇关于在node.js中读取二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆