我试图追加一个字符串到日志文件。但是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'

有什么简单的方法吗?


当前回答

对于偶尔的追加,你可以使用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');

但如果重复向同一个文件追加,重用文件句柄会好得多。

其他回答

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!');
});

文档

我包装了async fs。appendFile变成一个基于promise的函数。希望它能帮助其他人看到这是如何运作的。

    append (path, name, data) {

        return new Promise(async (resolve, reject) => {

            try {

                fs.appendFile((path + name), data, async (err) => {

                    if (!err) {

                        return resolve((path + name));

                    } else {

                        return reject(err);

                    }

                });

            } catch (err) {

                return reject(err);

            }

        });

    }
fd = fs.openSync(path.join(process.cwd(), 'log.txt'), 'a')
fs.writeSync(fd, 'contents to append')
fs.closeSync(fd)

对于偶尔的追加,你可以使用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');

但如果重复向同一个文件追加,重用文件句柄会好得多。

如果你想要一种简单而无压力的方法在文件中逐行写入日志,那么我推荐fs-extra:

const os = require('os');
const fs = require('fs-extra');

const file = 'logfile.txt';
const options = {flag: 'a'};

async function writeToFile(text) {
  await fs.outputFile(file, `${text}${os.EOL}`, options);
}

writeToFile('First line');
writeToFile('Second line');
writeToFile('Third line');
writeToFile('Fourth line');
writeToFile('Fifth line');

使用Node v8.9.4测试。