【问题标题】:How to update data into a file in a particular position in js如何将数据更新到js中特定位置的文件中
【发布时间】:2017-11-17 18:18:30
【问题描述】:

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

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

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

【问题讨论】:

  • 尝试使用像 github.com/tmpvar/jsdom 这样的解析器,你为什么要标记 angularjs :)
  • 嗨 codtex 因为这与 js 相关,一些专家喜欢可能来自 angular js...:)

标签: javascript angularjs node.js mean-stack fs


【解决方案1】:

你可以这样做:

  • 找到要插入字符串的索引
  • 对源字符串进行切片并插入新字符串

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

【讨论】:

    【解决方案2】:

    这不是仅使用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 遍历。

    【讨论】:

      【解决方案3】:

      为什么不在 jquery 中做呢。

      使用 for 循环来做这样的事情:

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

      希望它有效。

      【讨论】:

        猜你喜欢
        • 2019-02-27
        • 1970-01-01
        • 2015-08-29
        • 1970-01-01
        • 2013-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-29
        相关资源
        最近更新 更多