javascript - 如何使用 Node js 将一些额外的数据添加到现有文件中

标签 javascript jquery html node.js xmlnode

我有一个这样的文件

<?xml version="1.0" encoding="utf-8"?>
<Quiz>
<title>Matching</title>

/* Rewrite */
<questions>
<question>Can be passed on from the environment to the individual. This can be from a person, insects or from the physical environment. </question>
<answer>Communicable</answer>
</questions>
/* Rewrite End */

</quiz>

现在我想在 </quiz> 之前添加一些数据标签,所以它看起来像这样:

 <?xml version="1.0" encoding="utf-8"?>
<Quiz>
<title>Matching</title>


<questions>
<question>Can be passed on from the environment to the individual. This can be from a person, insects or from the physical environment. </question>
<answer>Communicable</answer>
</questions>

<questions>
<question>Some Txt</question>
<answer>Some Txt</answer>
</questions>


</quiz>

我正在使用

fs.writeFile("Templatexml.xml", data["message"] , function(err) {
  if(err) {
    console.log(err);
  } else {
    console.log("The file was saved!");
  }
});

每次我想读取文件并在此文件上写入额外内容时,它都会完全重写该文件,我该怎么做?

最佳答案

我有一个解决你问题的办法.. 像这样格式化你的 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<Quiz>
<title>Matching</title>
/* Rewrite */
<questions>
<question>Can be passed on from the environment to the individual. This can be from    person, insects or from the physical environment. </question>
<answer>Communicable</answer>
</questions>
//cursor
</quiz>

以及附加新数据的代码:

var fs = require("fs");
var addData = "<questions><question>Some Txt</question><answer>Some Txt</answer>     </questions>";
var cursor = "//cursor";
addData += cursor;
fs.readFile("Templatexml.xml", "utf-8",function(err,data) {
    if(err) {
        console.log(err);
        return;
     }
    var newData = data.replace(/\/\/cursor/,addData);
    fs.writeFile("Templatexml.xml", newData , function(err) {
    if(err) {
            console.log(err);
            return;
     } 
     console.log("done");
    });
});

关于javascript - 如何使用 Node js 将一些额外的数据添加到现有文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24426453/

相关文章:

javascript - 将 data 属性插入 url

javascript - 使用 Jquery 用除 div 之外的任何标签包装文本?

javascript - jquery select-box - 我怎样才能有两个不同宽度的输入

javascript - jQuery .validate() 不适用于动态创建的表行

javascript 正则表达式修复不替换图像 url

javascript - 来自 Google/Bing 的带有自动完成功能的自定义框。有没有办法读取接收到的json文件?

javascript - console.log 中的 %j 说明符不包括某些属性

javascript - 如何从@google-cloud/storage读取文件?

html - 为什么我的导航栏中的文本重叠?

html - 为什么我的边框不圆 Angular ?