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 个解决方案
#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 :
您既不需要读取文件的全部内容,也不需要使用replace来执行此操作。您可以从固定位置覆盖内容 - 此处为fileSize-7,长度为“ ”+ 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.
这将有效地加快性能。
#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 :
您既不需要读取文件的全部内容,也不需要使用replace来执行此操作。您可以从固定位置覆盖内容 - 此处为fileSize-7,长度为“ ”+ 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.
这将有效地加快性能。