How To Update Data Into A File In A Particular Position In Js
I have a file with the data as follows, Test.txt,
/////Need to append data at this point/////
Solution 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('<divclass="divcenter">') + '<divclass="divcenter">'.length; var result = file_content.slice(0, idx) + str + file_content.slice(idx); });
Solution 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.
Solution 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.
Post a Comment for "How To Update Data Into A File In A Particular Position In Js"