gpt4 book ai didi

javascript - js中如何将数据更新到文件中特定位置

转载 作者:行者123 更新时间:2023-11-30 06:51:23 24 4
gpt4 key购买 nike

我有一个包含如下数据的文件,

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">');
});

但是找到索引后如何追加呢?

最佳答案

你可以这样做:

  • 找到要插入字符串的索引
  • 分割源字符串并插入新字符串

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

关于javascript - js中如何将数据更新到文件中特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44564373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com