How to add some extra data to an existing file using node js

北战南征 提交于 2019-12-12 04:05:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!