新月到来后,如何创建新文件夹并在其中写入新日志?

时间:2019-08-29 06:11:32

标签: node.js

每天都会创建一些杂志。如何确保在新的月份到来时创建一个文件夹并将所有日志写入那里。因此,每到一个新月来。

function formatDate(date) {
    var monthNames = [
        "January", "February", "March",
        "April", "May", "June", "July",
        "August", "September", "October",
        "November", "December"
    ];
    var day = date.getDate();
    var monthIndex = date.getMonth();
    var year = date.getFullYear();
    return day + '_' + monthNames[monthIndex] + '_' + year;
}

function formatTime(time) {
    var hours = time.getHours();
    var minutes = time.getMinutes();
    var seconds = time.getSeconds();
    return hours + '_' + minutes + '_' + seconds;
}

var ws = fs.createWriteStream(`./logs/file-${formatDate(new Date())}-${formatTime(new Date())}.log`, {
    'flags': 'w',
    'encoding': 'utf8'
});

process.stdout.wr = process.stdout.write;
process.stdout.er = process.stderr.write;

process.stdout.write = function (mes, c) {
    ws.write(mes + '\r\n');
    process.stdout.wr(mes, c);
};

process.stderr.write = function (mes, c) {
    ws.write(mes + '\r\n');
    process.stdout.er(mes, c);
};

1 个答案:

答案 0 :(得分:0)

如果您想知道每个特定时间如何执行功能,我可以向您推荐npm包Later.js。如果您的代码有问题,请更好地为其他用户写问题