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

时间:2017-06-15 09:51:55

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

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?

3 个答案:

答案 0 :(得分: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);
    });
    

答案 1 :(得分:-1)

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.

答案 2 :(得分:-1)

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.