分享好友 编程语言首页 频道列表

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

nodejs文章/教程  2023-02-09 05:240

注意: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)
    }
})
 

这篇博客.


总结

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

查看更多关于【nodejs文章/教程】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
打造自己的 nodejs 静态文件服务器(帖子内容,直接复制别人的)
用NodeJS打造你的静态文件服务器在《The Node Beginner Book》的中文版(http://nodebeginner.org/index-zh-cn.html)发布之后,获得国内的好评。也有同学觉得这本书略薄,没有包含进阶式的例子。@otakustay同学说:“确实,我的想法是在这之上补一个简单的MV

0评论2023-02-10548

NodeJS无所不能:细数10个令人惊讶的NodeJS开源项目
在几年的时间里,NodeJS逐渐发展成一个成熟的开发平台,吸引了许多开发者。有许多大型高流量网站都采用NodeJS进行开发,像PayPal,此外,开发人员还可以使用它来开发一些快速移动Web框架。  除了Web应用外,NodeJS也被应用在许多方面,本文盘点了NodeJS在其

0评论2023-02-10598

Linux环境下的Nodejs linux安装基本环境
最近在学习Node.js,在window下总是觉得不那么爽快。最简单而且环保的方法是在虚拟机中安装一个Linux。 { 1.Linux:家中的Linux为Centos。 2.VirtuallyBox: 开启2块网卡。第一个选Host-Only目的是为了让虚拟机通上网。第二块选Bridge Adapter,这是为了

0评论2023-02-09597

nodejs package.json说明
{"name": "test", //项目名称(必须),由小写英文字母、数字和下划线,不能含空格"version": "1.0.0", //项目版本(必须)"description": "This is for study gulp project !", //项目描述(必须)"homepage": "", //项目主页url " key

0评论2023-02-09473

017 nodejs取参四种方法req.body,req.params,req.param,req.body
摘要: nodejs取参四种方法req.body,req.params,req.param,req.body 获取请求很中的参数是每个web后台处理的必经之路,nodejs提供了四种方法来实现。获取请求很中的参数是每个web后台处理的必经之路,nodejs的 express框架 提供了四种方法来实现。req.bodyre

0评论2023-02-09446

nodejs查看本机hosts文件域名对应ip
const dns = require('dns')dns.lookup('domainName', function(err, result) {console.log(result)}) related:https://***.com/questions/36689536/how-to-resolve-hostname-to-an-ip-address-in-node-js

0评论2023-02-09475

nodejs工程拷贝后运行报module找不到问题
工程文件夹通过复制黏贴到另外一个地方,运行后报错 “can`t find module 某某某”,查看原因:输入node 进入控制台,输入console.log(module.paths)查看当前nodejs查找module的路径,如果没有工程里的node_modules,通过module.paths.push加入,检查是否有效

0评论2023-02-09947

C# Socket TCP Server & Client & nodejs client cctv5体育节目表
要调试公司某项目里的一个功能,因为要准备测试环境,趁这个机会重温了一下Socket(全还给老师了 -_-#),做个备份。C# Serverstatic void Main(string[] args){int port = 81;string host = "192.168.1.151";//创建终结点IPAddress ip = IPAddress.Parse(hos

0评论2023-02-09810

nodejs微信公众号快速开发|自定义关键字回复
一点说明:nodejs 微信api 扩展,集成大部分功能。案例https://github.com/leiroc/node-wxeasy-example 上传example中文件到服务器 ,然后 npm install 成功https://github.com/leiroc/node-wxeasy-exampleBUG and NEWS增加客户功能增加模板消息增加扫描带参数

0评论2023-02-09404

Centos 32位 安装 NodeJS
yum -y install gcc make gcc-c++ openssl-devel wget下载源码及解压:wget https://nodejs.org/dist/v6.9.5/node-v6.9.5.tar.gztar -zvxf node-v0.10.26.tar.gz编译及安装:cd node-v0.10.26 切换目录,执行./configuremakemake install验证是否安装配置成功

0评论2023-02-09537

nodejs一部分基本模块及作用 node 引入一个模块的过程是什么
收集了NodeJS开发中常用的一些模块。MVC框架 -ExpressExpress 是轻量灵活的Nodejs Web应用框架,它可以快速地搭建网站。Express框架建立在Nodejs内置的Http模块上,并对Http模块再包装,从而实际Web请求处理的功能。它支持多种前端模板,如Jade, EJS等。它是T

0评论2023-02-09868

nodejs定时启动程序 nodejs开机自启
npm install node-schedule# 或yarn add node-schedule使用(second、minute、hour、  date、dayOfWeek、month、year)每分钟第1秒执行一次const schedule = require("node-schedule");var rule = new schedule.RecurrenceRule();rule.second = 1;// 秒schedu

0评论2023-02-09406

更多推荐