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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM