如何在文件中找到一系列字节并将它们替换为另一个缓冲区?

How can I find a series of bytes in a file and replace them with another buffer?

基本上我正在使用 fs.readFile 在 NodeJS 中读取文件,而这个 returns 文件的缓冲区。

然后我想在这个缓冲区中找到特定的字节模式,并用相同大小的新缓冲区替换它们(或者如果它较小,则将其余部分填充为 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 is all you need to find the position, then use 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);
 }
}