如何在没有string比较的情况下快速在node.js文件中附加节点
这里提出了一个解决scheme: 如何附加到文件的某一行?
我在这里复制解决scheme以供参考
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!'); }); });
但是,上面的解决scheme需要string匹配'</xml>'
string。 如果我们知道文件的最后一行总是'</xml>'
,那么有没有办法通过消除string比较来加速代码? 有没有另一种更有效的方法来完成这项任务?
您既不需要阅读文件的全部内容,也不需要使用replace
。 您可以覆盖固定位置的内容 – 这里是fileSize-7
,长度为'</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') }) });
这将有效加快性能。