user3586498
user3586498

Reputation: 45

How to append to certain line of file?

I want to append to a file but I want to start appending before </xml> tag end. appears. How can I do that?

var fs = require("fs");
fs.appendFile('somefile.xml', 'Content')

I have sth like this but it insert 'content' at the end of file, and I want it in specific line before specific 'keyword'

Upvotes: 0

Views: 1587

Answers (2)

Michael Kay
Michael Kay

Reputation: 163524

A good approach is to split the file into a wrapper file and a body file. The wrapper just contains the outermost tag and an entity reference to the body file. Your program can then append to the end of the body file, whereas anyone reading the file as XML should read the wrapper file. The wrapper file will look something like this:

<!DOCTYPE xml [
<!ENTITY e SYSTEM "body.xml">
]>
<xml>&e;</xml>

Using "xml" as an element name, by the way, is bad practice. All names starting "xml" are reserved for future use by W3C.

This approach may not work if you're reading the XML in a browser. I think that some browsers' XML parsers don't support external entities.

Upvotes: 1

cgf
cgf

Reputation: 3509

This might not be the easiest option, but at least it should get the job done. Haven't tested it, so it might require some changes. It reads the file and when it's done, it creates the new file by removing the </xml> tag, adding the content and then adding the </xml> tag again at the end.

var fs = require('fs');

var xmlFile;
fs.readFile('someFile.xml', function (err, data) {
  if (err) throw err;
  xmlFile = data;

  var newXmlFile = xmlFile.replace('</xml>', '') + 'Content' + '</xml>';

  fs.writeFile('someFile.xml', newXmlFile, function (err) {
    if (err) throw err;
    console.log('Done!');
  }); 
});

Upvotes: 2

Related Questions