Reading binary data in node.js(在 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 字节.这是为什么?我已经对 readFileSync 和 toString 说明了二进制编码.我也尝试过 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 中读取二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 node.js 中读取二进制数据
基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
