Javascript 如何使用node js向现有文件添加一些额外数据

Javascript 如何使用node js向现有文件添加一些额外数据,javascript,jquery,html,node.js,xmlnode,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 fr

我有一个这样的文件

<?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>

每次我想读取文件并在文件上写入额外内容时,它都会完全重写文件。我如何才能做到这一点?

我有一种黑客解决方案来解决您的问题。。 将xml文件格式化如下:

 <?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>
<?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");
    });
});
var fs=require(“fs”);
var addData=“Some TxtSome Txt”;
var cursor=“//cursor”;
addData+=光标;
readFile(“Templatexml.xml”,“utf-8”,函数(err,data){
如果(错误){
控制台日志(err);
返回;
}
var newData=data.replace(/\/\/cursor/,addData);
writeFile(“Templatexml.xml”、新数据、函数(err){
如果(错误){
控制台日志(err);
返回;
} 
控制台日志(“完成”);
});
});

IMHO这不是一个重复的问题,因为另一个问题是关于在文件末尾追加内容,这个问题是关于在文件中间插入内容。我想在现有数据之间添加数据。我不知道我该怎么做。所以只有我提出了一个问题。
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");
    });
});