最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

我怎样才能找到一系列字节的文件,并与另一个缓冲区替换它们?

IT培训 admin 6浏览 0评论

我怎样才能找到一系列字节的文件,并与另一个缓冲区替换它们?

基本上我阅读使用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);
 }
}
发布评论

评论列表 (0)

  1. 暂无评论