如何将数据更新到js中特定位置的文件中
我有一个文件的数据如下,
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">'); });
但是如何find索引后追加?
你可以这样做:
- find你想要插入你的string的索引
-
切片源string并插入新的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); });
这不是使用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遍历string。
为什么不在jQuery中做。
使用循环来做到这一点:
var uiDiv = $(".divcenter"); for(var i=0; i<data.length; i++){ uiDiv.append("<p>'"+data[i]+"'</p>"); }
希望它的作品。
- 如何用MEAN和sails.js开始一个新的项目
- HTML和JSON响应的相同URL
- 如何使用angular度节点应用程序的护照?
- 如果只有本地的Angular App将其称为控制器,则执行路由
- AngularJS和ExpressJS:如何阅读由$ http.put()发送的内容
- 发表angularjsforms到nodejs Express(Bad request)
- 从node.js中以angularjs的forms使用json数据作为后端和sql数据库
- 将https请求从angular度发送到nodejs。 无法发送任何数据
- 当所有组件都在一个文件中时,Angular App就可以工作,但是当组件在不同的文件中时会引发'nomod'错误