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 中读取二进制数据
基础教程推荐
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bokeh Div文本对齐 2022-01-01
