Skip to content Skip to sidebar Skip to footer

How To Append To Certain Line Of File?

I want to append to a file but I want to start appending before tag end. appears. How can I do that? var fs = require('fs'); fs.appendFile('somefile.xml', 'Content')

Solution 1:

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!');
  }); 
});

Solution 2:

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.


Post a Comment for "How To Append To Certain Line Of File?"