如发现博文存在问题,可以随时滴滴我

Nodejs怎样在服务端写定时脚本,自动备份MongoDB数据库,并记录日志

注意:mongod服务需提前开启

定时任务

安装模块 npm install node-schedule -S

使用方法

const schedule = require('node-schedule');//引入定时任务模块

function scheduleCronstyle(){
    schedule.scheduleJob('10 * * * * *', function(){
        console.log('scheduleCronstyle:' + new Date());//定时执行内容
    }); 
}
scheduleCronstyle();
 

通配符参数介绍

*  *  *  *  *  *
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ |
│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
│ │ │ │ └───── month (1 - 12)
│ │ │ └────────── day of month (1 - 31)
│ │ └─────────────── hour (0 - 23)
│ └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)
 

打开CMD执行命令

安装模块 npm install child_process -S

使用方法

const process = require('child_process');//引入cmd模块
const cmd = 'ipconfig';//cmd执行内容

process.exec(cmd, function(error, stdout, stderr) {
    if (error) {
        console.log('Error:'+ error);//失败
    } else if (stderr.lenght > 0) {
        console.log('Stderr:'+stderr.toString())//标准错误输出
    } else {
        console.log('Success')//成功
    }
});
 

日志写入

安装模块 npm i fs -S

使用方法

const fs = require('fs');//引入fs模块

let year = (new Date()).getFullYear();//获取年
let month = ((new Date()).getMonth()+1) > 9 ? ((new Date()).getMonth()+1) : '0' + ((new Date()).getMonth()+1);//获取月
let date = (new Date()).getDate() > 9 ? (new Date()).getDate() : '0' + (new Date()).getDate();//获取日
let hour = (new Date()).getHours() > 9 ? (new Date()).getHours() : '0' + (new Date()).getHours();//获取时
let minute = (new Date()).getMinutes() > 9 ? (new Date()).getMinutes() : '0' + (new Date()).getMinutes();//获取分
let seconds = (new Date()).getSeconds() > 9 ? (new Date()).getSeconds() : '0' + (new Date()).getSeconds();//获取秒
let str = `${year}-${month}-${date} ${hour}:${minute}:${seconds} 备份`
fs.writeFile(path,`\n${str}`, {flag:'a+'},(err) =>{  //path指的是存储文件路径,如: C:\\backup\\[数据库名]\\.log  我这里存储在备份数据库目录下
    if(err){
        console.log(err)
    }
})
 

更多fs模块的存储读取请查看我这篇博客.


总结

const schedule = require('node-schedule');//引入定时任务模块
const process = require('child_process');//引入cmd模块
const fs = require('fs');//引入fs模块

//cmd执行内容
//数据库地址及端口 如:127.0.0.1:27017
//要备份的数据库名称 如:test
//备份路径如:C:\\backup
const cmd = 'mongodump -h [数据库地址:端口] -d [要备份的数据库名称] -o [备份路径]';

function scheduleCronstyle(){
    schedule.scheduleJob('0 0 23 * * 7', function(){  //每周日的23时整
        process.exec(cmd, function(error, stdout, stderr) {  //在cmd中执行上方定义的命令
            if (error) {
                console.log('Error:'+ error); //错误
            } else if (stderr.lenght > 0) {
                console.log('Stderr:'+stderr.toString())  //标准性错误
            } else {
                //成功之后写入日志
                let year = (new Date()).getFullYear();//获取年
                let month = ((new Date()).getMonth()+1) > 9 ? ((new Date()).getMonth()+1) : '0' + ((new Date()).getMonth()+1);//获取月
                let date = (new Date()).getDate() > 9 ? (new Date()).getDate() : '0' + (new Date()).getDate();//获取日
                let hour = (new Date()).getHours() > 9 ? (new Date()).getHours() : '0' + (new Date()).getHours();//获取时
                let minute = (new Date()).getMinutes() > 9 ? (new Date()).getMinutes() : '0' + (new Date()).getMinutes();//获取分
                let seconds = (new Date()).getSeconds() > 9 ? (new Date()).getSeconds() : '0' + (new Date()).getSeconds();//获取秒
                let str = `${year}-${month}-${date} ${hour}:${minute}:${seconds} 备份`
                fs.writeFile(path,`\n${str}`, {flag:'a+'},(err) =>{ //path 为存储路径 如:C:\\backup\\[数据库名]\\.log  我这里存储在备份数据库目录下
                    if(err){
                        console.log(err)
                    }
                })
            }
        });
    }); 
}

scheduleCronstyle();
 

最后在终端中使用node执行该js文件就可以定时备份数据库并记录备份时间

child_process
posted @ 2020-07-19 03:19  webxue  阅读(839)  评论(0编辑  收藏  举报