Rob*_*sen 6 javascript binary node.js
我在node.js中读取二进制数据时遇到问题.这就是我做的:
$ 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 .
$
Run Code Online (Sandbox Code Playgroud)
注意当使用节点读取时,如何在索引0x29处插入0xc2字节.这是为什么?我说二进制编码都以readFileSync和toString.我也试过ascii,但后来我得到了一个不同的,同样错误的结果.
只是为了添加更多信息,发生这种情况的原因是因为您正在将字符串传递给stdout.write(),Buffer在写入之前将其隐式转换回a ,并且在Node.js REPL中使用此特定子字符串定位时二进制文件的0x28,您得到的行为是您描述的:
> new Buffer('\u0010\u00a0')
<Buffer 10 c2 a0>
Run Code Online (Sandbox Code Playgroud)
因此,正如正确建议的@TJCrowder一样,以下是修复脚本的方法:
var fs = require('fs'),
binary = fs.readFileSync('./binary');
process.stdout.write(binary.slice(0, 48));
Run Code Online (Sandbox Code Playgroud)
这也使用Buffer#slice()代替String#substring()。
| 归档时间: |
|
| 查看次数: |
16174 次 |
| 最近记录: |