且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将数据更新到js中特定位置的文件中

更新时间:2023-10-09 11:43:40

您可以这样:

  • 找到要在其中插入字符串的索引
  • 切片源字符串并插入新字符串

  • find the index where you want to insert your string
  • slice the source string and insert new string

fs.readFile(Test.txt, function read(err, data) {
   if (err) {
      throw err;
   }
   var file_content = data.toString();
   var str = "<p>grapes</p>
           <p>banana</p>   
           <p>orange</p>
           <p>apple</p>
           <p>gua</p>";
   var idx = file_content.indexOf('<div class="divcenter">') + '<div class="divcenter">'.length;
   var result = file_content.slice(0, idx) + str + file_content.slice(idx);
});