我正在尝试将字符串追加到日志文件。 可是writeFile每次写入字符串以前都会擦除内容。 html
fs.writeFile('log.txt', 'Hello Node', function (err) { if (err) throw err; console.log('It\'s saved!'); }); // => message.txt erased, contains only 'Hello Node'
任何想法如何以简单的方式作到这一点? node
对于偶尔的追加,您能够使用appendFile
,每次调用它时都会建立一个新的文件句柄: api
异步地 : app
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 。 ui
fd = fs.openSync(path.join(process.cwd(), 'log.txt'), 'a') fs.writeSync(fd, 'contents to append') fs.closeSync(fd)
Node.js 0.8具备fs.appendFile
: this
fs.appendFile('message.txt', 'data to append', (err) => { if (err) throw err; console.log('The "data to append" was appended to file!'); });
文献资料 spa
这是完整的脚本。 填写文件名并运行它,它应该能够工做! 这是有关脚本背后逻辑的视频教程 。 日志
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);
您须要打开它,而后写它。 code
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方法进行追加。