如何将数据更新到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>"); }
希望它的作品。
- Kibana不加载样式表
- Nodejs http://test.dev:3000/api/profile。 没有'Access-Control-Allow-Origin'标题Origin'http:// localhost:9000'
- 使用Node + Express web API的angular度应用程序返回JSON资源vs服务器端模板引擎
- PassportJS – 在将有效载荷数据传递给passport.authenticate作为请求参数之前获取
- 节点服务器拦截从angular(http)到java后端的所有请求
- 是否有可能在哈斯克尔和前端用JavaScript写后端?
- 如何在angularjs中使用ng-class应用css
- 问题在angularjs routeProvider
- 如何简化发送(文件,模型)的angular度和FormData