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

我有一个文件的数据如下,

Test.txt, <template class="get" type="amp-mustache"> <div class="divcenter"> /////Need to append data at this point///// </div> </template> 

我有如下的数据

 [ {'text':'<p>grapes</p>'}, {'text':'<p>banana</p>'}, {'text':'<p>orange</p>'}, {'text':'<p>apple</p>'}, {'text':'<p>gua</p>'} ] 

追加数据后应该是,

  <template class="get"> <div class="divcenter"> <p>grapes</p> <p>banana</p> <p>orange</p> <p>apple</p> <p>gua</p> </div> </template> 

我的代码,

 fs.readFile(Test.txt, function read(err, data) { if (err) { throw err; } var file_content = data.toString(); var c = file_content.indexOf(' <div class="divcenter">'); }); 

但是如何find索引后追加?

你可以这样做:

  • find你想要插入你的string的索引
  • 切片源string并插入新的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); }); 

这不是使用substr的最优雅的方法

 var needle = '<div class="divcenter">'; var newString = file_content.substr(0, c + needle.length) + '__NEW_STRING__' + file_content.substr(needle.length - 1); 

编辑:

更好的方法是使用cheerio作为DOM遍历string。

为什么不在jQuery中做。

使用循环来做到这一点:

 var uiDiv = $(".divcenter"); for(var i=0; i<data.length; i++){ uiDiv.append("<p>'"+data[i]+"'</p>"); } 

希望它的作品。