Javascript fs writefile 新行不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30283509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:55:25  来源:igfitidea点击:

fs writefile new line not working

javascriptnode.js

提问by anonprophet

i want log my user command

我想记录我的用户命令

function saveLog (nick, command) {
    var file = 'log/' + nick + '.log';
    var datetime = '[' + getDateTime() + '] ';
    var text = datetime + command + '\r\n';
    fs.writeFile(file, text, function (err) {
        if (err) return console.log(err);
        console.log(text);
    });
}

the function i made is fine, but it didnt save the log in new line, its just replace text / rewrite the file. whats im missing ?

我做的功能很好,但它没有将日志保存在新行中,它只是替换文本/重写文件。我错过了什么?

thanks

谢谢

回答by lyHymanal

fs.writeFilewrites a WHOLE NEW file. What your are looking for is fs.appendFilewhich will make the file if it doesn't exist and append to it. Documentation here.

fs.writeFile写入一个全新的文件。您正在寻找的是fs.appendFile,如果该文件不存在并附加到该文件中,它将生成该文件。文档在这里

function saveLog (nick, command) {
    var file = 'log/' + nick + '.log';
    var datetime = '[' + getDateTime() + '] ';
    var text = datetime + command + '\r\n';
    fs.appendFile(file, text, function (err) {
        if (err) return console.log(err);
        console.log('successfully appended "' + text + '"');
    });
}