我怎样才能找到一系列字节的文件,并与另一个缓冲区替换它们?
基本上我阅读使用fs.readFile
一个的NodeJS文件,此返回文件的缓冲区。
然后,我想找到的字节这个缓冲区内一定的模式,并与同样大小的一个新的缓冲区替换它们(或垫剩下的00,如果是较小的。)
我尝试了缓冲区设置为字符串,并使用.replace
,但会导致文件大小增加一倍,更何况它只是是不是真的实用。
let data = await readFile('mytest.exe');
var pattern = new Buffer.from([
0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90
])
与文件的字节交叉参考图案,并发现它,转换一个字符串,它是32个字节缓冲,并覆盖与32个字节字符串的缓冲区,然后将其保存在文件中。
回答如下:Buffer.indexOf是所有你需要找到的位置,然后使用Buffer.copy来覆盖它。
/* Replaces all occurences of "pattern" in the "data" with "replace",
if "replace" is shorter than "pattern" the rest will be filled with 0s, a longer "replace" will get trimmed of */
function replace(/*Buffer*/ data, /*Buffer*/ pattern, /*Buffer*/ replace) {
let position = data.indexOf(pattern);
while (position !== -1) {
data.fill(0, /*from*/ position, /*to*/ position + pattern.length);
replace.copy(
/*to*/ data,
/*at*/ position,
/*from*/ 0,
/*to*/ pattern.length
);
// continue search:
position = data.indexOf(pattern, /*starting at*/ position + pattern.length + 1);
}
}
我怎样才能找到一系列字节的文件,并与另一个缓冲区替换它们?
基本上我阅读使用fs.readFile
一个的NodeJS文件,此返回文件的缓冲区。
然后,我想找到的字节这个缓冲区内一定的模式,并与同样大小的一个新的缓冲区替换它们(或垫剩下的00,如果是较小的。)
我尝试了缓冲区设置为字符串,并使用.replace
,但会导致文件大小增加一倍,更何况它只是是不是真的实用。
let data = await readFile('mytest.exe');
var pattern = new Buffer.from([
0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90
])
与文件的字节交叉参考图案,并发现它,转换一个字符串,它是32个字节缓冲,并覆盖与32个字节字符串的缓冲区,然后将其保存在文件中。
回答如下:Buffer.indexOf是所有你需要找到的位置,然后使用Buffer.copy来覆盖它。
/* Replaces all occurences of "pattern" in the "data" with "replace",
if "replace" is shorter than "pattern" the rest will be filled with 0s, a longer "replace" will get trimmed of */
function replace(/*Buffer*/ data, /*Buffer*/ pattern, /*Buffer*/ replace) {
let position = data.indexOf(pattern);
while (position !== -1) {
data.fill(0, /*from*/ position, /*to*/ position + pattern.length);
replace.copy(
/*to*/ data,
/*at*/ position,
/*from*/ 0,
/*to*/ pattern.length
);
// continue search:
position = data.indexOf(pattern, /*starting at*/ position + pattern.length + 1);
}
}