node.js - 使用 NodeJS/memoryjs 将 TypeScript 缓冲区解码为 JSON 对象
我正在尝试使用 mermoryjs.readBuffer() 从 缓冲区 获取一个 JSON 对象,我已经尝试了一段时间,不确定接下来该怎么办。以下是我尝试过的方法:
import { readBuffer } from 'memoryjs';
let buffer: Buffer = readBuffer(process, address, bufferLength);
console.log(buffer);
// (correctly) OUTPUTS -> <Buffer 88 77 b3 10 00 00 00 00 00 00 00 00 60 d5 69 1b 06 00 00 00 16 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 40 c2 52 16 01 00 00 00 00 9a 8f 07 00 00 ... 6 more bytes>
console.log(buffer.toJson());
// OUTPUS:
{
type: 'Buffer',
data: [
136, 119, 179, 16, 0, 0, 0, 0, 0, 0, 0, 0,
96, 213, 105, 27, 6, 0, 0, 0, 22, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
64, 194, 82, 22, 1, 0, 0, 0, 0, 154, 143, 7,
0, 0, 0, 0, 0, 0, 0, 0
]
}
console.log(JSON.parse(JSON.stringify(buffer)));
// OUTPUS:
{
type: 'Buffer',
data: [
136, 119, 179, 16, 0, 0, 0, 0, 0, 0, 0, 0,
96, 213, 105, 27, 6, 0, 0, 0, 22, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
64, 194, 82, 22, 1, 0, 0, 0, 0, 154, 143, 7,
0, 0, 0, 0, 0, 0, 0, 0
]
}
console.log(buffer.toString());
// OUTPUTS: �w�►`�i♠▬�R▬☺��
然后当它尝试这个时:
console.log(JSON.parse(buffer.toString()));
// OUTPUTS:
SyntaxError: Unexpected token � in JSON at position 0
at JSON.parse (<anonymous>)
使用 structron 的 read() 函数(npm 包 https://www.npmjs.com/package/structron)
import Struct = require('structron'); // doing " import Struct from 'structron' " gives an import error
let struct = new Struct();
console.log(this.struct.read(buffer, address));
// OUPUTS: {}
我正在实时读取一个应用程序的内存,当我在应用程序中勾选一个复选框时,我可以看到 buffer 变量从 00 变为 01,以及内脏变化,所以我认为问题不在于以错误的方式获取缓冲区数据(用错误的 address 或 process)。
我在考虑是否可以将 buffer.data 中的整数数组解码/反序列化为一个 JSON 对象,但我不确定是否有办法做到这一点。
任何输入都会对我有很大帮助。提前谢谢你。
答案#1
将缓冲区序列化为明文的最佳方法可能是将其转换为 base64:
const buf = Buffer.from("asdf");
// this is a string you can store in a JSON object somewhere
const serialized = x.toString("base64");
console.log(serialized); // YXNkZg==
// you can get the serialized base64 from a JSON object
const deserialized = Buffer.from(serialized, "base64");
console.log(deserialized); // <Buffer 61 73 64 66>
console.log(deserialized.toString("utf8")); // asdf
请注意,如果你能,你应该将缓冲区直接写入文件,因为 base64 比原始二进制数据更占空间。
答案#2
JSON.parse(body.toString())
这对我有效。
