我有一个这样的文件
<?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/