问题
I have a file like 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>
Now i want to add some data before </quiz>
tag so it will look like this:
<?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>
I am using
fs.writeFile("Templatexml.xml", data["message"] , function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
It fully rewrites the file every time I want to read the file and and write the extra content on this file how can i do this?
回答1:
I have a kind of hacky solution for your problem.. format you xml file like 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 person, insects or from the physical environment. </question>
<answer>Communicable</answer>
</questions>
//cursor
</quiz>
and the code for appending new data:
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");
});
});
来源:https://stackoverflow.com/questions/24426453/how-to-add-some-extra-data-to-an-existing-file-using-node-js