简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM