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

时间:2014-06-26 09:03:50

标签: javascript jquery html5 node.js xmlnode

我有一个像This

这样的文件
<?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!");
  }
});

每次我想要读取文件时都会完全重写文件,并在此文件上写下额外的内容,我该怎么办呢?

1 个答案:

答案 0 :(得分:1)

我有一个针对你的问题的hacky解决方案.. 格式化你的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");
    });
});