Nikos Tsagkas
Nikos Tsagkas

Reputation: 1307

How to append a node in an XML file with node.js fast without string comparison

A solution is proposed here: How to append to certain line of file?

I copy the solution here for reference

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

However the solution above requires string matching of the '</xml>' string. If we know that the last line of the file will always be '</xml>' is there any way to speed up the code by eliminating the need for string comparison? Is there an another more efficient way to do this task?

Upvotes: 1

Views: 1894

Answers (1)

davidkonrad
davidkonrad

Reputation: 85578

You neither need to read the entire content of the file nor to use replace for doing that. You can overwrite the content from a fixed position - here fileSize-7, length of '</xml>'+1 :

var fs = require('fs');

//content to be inserted
var content = '<text>this is new content appended to the end of the XML</text>';

var fileName = 'someFile.xml',
    buffer = new Buffer(content+'\n'+'</xml>'), 
    fileSize = fs.statSync(fileName)['size'];

fs.open(fileName, 'r+', function(err, fd) {
    fs.write(fd, buffer, 0, buffer.length, fileSize-7, function(err) {
        if (err) throw err
        console.log('done') 
    })  
});

This will effectively speed up the performance.

Upvotes: 2

Related Questions