我正在嘗試將字符串追加到日誌文件。 可是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方法進行追加。