1

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?

1 Answer 1

2

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.

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.