How to update data into a file in a particular position in js

岁酱吖の 提交于 2020-01-04 05:56:19

问题


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>

I have the data like below

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

After appending the data should be,

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

My code,

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?


回答1:


You could do like this :

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



回答2:


This is not the most elegant way with using only substr

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

Edit:

A more elegant way is to traverse the string as DOM using cheerio.




回答3:


Why not do in jquery.

Use for loop to do it like this:

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

Hope it works.



来源:https://stackoverflow.com/questions/44564373/how-to-update-data-into-a-file-in-a-particular-position-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!