3 回答

TA貢獻1818條經(jīng)驗 獲得超7個贊
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');

TA貢獻1847條經(jīng)驗 獲得超7個贊
appendFile
, appendFile
EMFILE
appendFile
WriteStream
.
appendFile
:
console.log(new Date().toISOString());[...Array(10000)].forEach( function (item,index) { fs.appendFile("append.txt", index+ "\n", function (err) { if (err) console.log(err); });});console.log(new Date().toISOString());
{ Error: EMFILE: too many open files, open 'C:\mypath\append.txt' at Error (native) errno: -4066, code: 'EMFILE', syscall: 'open', path: 'C:\\mypath\\append.txt' }
appendFile
var stream = fs.createWriteStream("append.txt", {flags:'a'});console.log(new Date().toISOString());[...Array(10000)].forEach( function (item,index) { stream.write(index + "\n");});console.log(new Date().toISOString());stream.end();
stream.end()
AutoClose:true

TA貢獻1895條經(jīng)驗 獲得超3個贊
使用createWriteStream的代碼為每次寫入創(chuàng)建一個文件描述符。因為它要求節(jié)點在寫入后立即關(guān)閉,因此log.end更好。
var fs = require('fs');
var logStream = fs.createWriteStream('log.txt', {'flags': 'a'});
// use {'flags': 'a'} to append and {'flags': 'w'} to erase and write a new file
logStream.write('Initial line...');
logStream.end('this is the end line');
- 3 回答
- 0 關(guān)注
- 520 瀏覽
添加回答
舉報