0

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?

2
  • IMHO this isn't a duplicate, as the other question is about appending to the end of a file, this question is about inserting something into the middle of a file. Commented Jun 26, 2014 at 9:32
  • i want to add data in between the Existing data. i dont know how can i do that. so only i opened a question. Commented Jun 26, 2014 at 9:32

1 Answer 1

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");
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.