我正在尝试将字符串追加到日志文件。 但是writeFile每次写入字符串之前都会擦除内容。
fs.writeFile('log.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
}); // => message.txt erased, contains only 'Hello Node'
任何想法如何以简单的方式做到这一点?
#1楼
对于偶尔的追加,您可以使用appendFile ,每次调用它时都会创建一个新的文件句柄:
const fs = require('fs');
fs.appendFile('message.txt', 'data to append', function (err) {
if (err) throw err;
console.log('Saved!');
});
const fs = require('fs');
fs.appendFileSync('message.txt', 'data to append');
但是,如果您重复追加到同一文件,最好重用文件handle 。
#2楼
fd = fs.openSync(path.join(process.cwd(), 'log.txt'), 'a')
fs.writeSync(fd, 'contents to append')
fs.closeSync(fd)
#3楼
Node.js 0.8具有fs.appendFile :
fs.appendFile('message.txt', 'data to append', (err) => {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
#4楼
这是完整的脚本。 填写文件名并运行它,它应该可以工作! 这是有关脚本背后逻辑的视频教程 。
var fs = require('fs');
function ReadAppend(file, appendFile){
fs.readFile(appendFile, function (err, data) {
if (err) throw err;
console.log('File was read');
fs.appendFile(file, data, function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
});
}
// edit this with your file names
file = 'name_of_main_file.csv';
appendFile = 'name_of_second_file_to_combine.csv';
ReadAppend(file, appendFile);
#5楼
您需要打开它,然后写它。
var fs = require('fs'), str = 'string to append to file';
fs.open('filepath', 'a', 666, function( e, id ) {
fs.write( id, 'string to append to file', null, 'utf8', function(){
fs.close(id, function(){
console.log('file closed');
});
});
});
这里有一些链接将有助于解释参数
编辑 :此答案不再有效,请查看新的fs.appendFile方法进行追加。