TypeScript/Node.js中使用memoryjs读取Buffer后无法解析为JSON对象怎么办
内存Buffer解析问题说明
核心操作背景
我正尝试通过memoryjs.readBuffer()从内存读取得到的Buffer数据中,解析出目标JSON对象,已经反复尝试多种方案仍未得到预期结果,以下是所有操作过程和对应的现象。
已完成的尝试与对应输出
基础读取逻辑验证
首先对目标进程指定内存地址执行读取操作,读取的原始Buffer输出如下,确认读取动作的基础流程正常:
import { readBuffer } from 'memoryjs'; let buffer: Buffer = readBuffer(process, address, bufferLength); console.log(buffer); // 原始Buffer输出(验证数据源有效) // <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>
Buffer序列化转JSON尝试
第一种方案是直接调用Buffer自带的序列化方法:
console.log(buffer.toJSON()); // 实际输出 // { // 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 // ] // }
第二种方案是通过JSON中转实现Buffer到JSON的转换:
console.log(JSON.parse(JSON.stringify(buffer))); // 实际输出和上面的结果完全一致 // { // 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 // ] // }
字符串转换与解析尝试
直接将Buffer转成默认编码的字符串:
console.log(buffer.toString()); // 实际输出为乱码:�w�►`�i♠▬�R▬☺��
尝试将转出的字符串直接传入JSON.parse解析:
console.log(JSON.parse(buffer.toString())); // 报错信息 // SyntaxError: Unexpected token � in JSON at position 0 // at JSON.parse (<anonymous>)
二进制结构解析尝试
使用structron(一款常用的二进制结构解析npm包)的read()方法尝试提取结构化数据,导入方式使用CommonJS语法(如果使用ESModule默认导入会直接抛出导入错误):
import Struct = require('structron'); // 执行" import Struct from 'structron' "会抛出导入错误 let struct = new Struct(); console.log(this.struct.read(buffer, address)); // 实际输出:{}
已排除的异常原因
通过实时数据变化验证:在被读取的目标应用界面勾选复选框时,可观测到buffer中对应的字节从00变为01,取消勾选时又变回00。该现象可证明:
- 传入
readBuffer的进程参数是正确的 - 传入的内存地址参数是正确的
- 读取到的内存内容和目标应用的运行状态直接关联,不存在读取错误内存区域的问题
当前的思路卡点
目前考虑或许可以将buffer.data中存储的整数数组,通过特定的解码/反序列化流程还原为对应的JSON对象,但暂时不确定可行的实现方案,需要相关的操作指导。
内容的提问来源于stack exchange,提问作者get_php_workin
相关产品推荐
相关产品推荐

