如何将数据更新到js中特定位置的文件中 [英] How to update data into a file in a particular position in js

查看:72
本文介绍了如何将数据更新到js中特定位置的文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a file with the data as follows,

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">');
});

但是找到索引后如何追加?

But how can I append after finding the index?

推荐答案

您可以这样:

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

  • 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);
});

这篇关于如何将数据更新到js中特定位置的文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆