Created
November 13, 2012 03:29
-
-
Save dead-horse/4063766 to your computer and use it in GitHub Desktop.
mongodb数据库定时备份
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* dump.js, dump mongodb. | |
* Copyright(c) 2012 Taobao.com | |
* Author: busi.hyy <[email protected]> | |
* | |
* 每天凌晨3点从mongo dump一份到指定文件夹,前缀为20121113_ | |
* 只保留最近七天的dump文件 | |
* Example: `node dump 127.0.0.1:27071 back database collection1 collection2 ...` | |
*/ | |
/** | |
* module dependences | |
*/ | |
var fs = require('fs'); | |
var spawn = require('child_process').spawn; | |
var argv = process.argv; | |
var mongoHost = process.argv[2]; | |
var baseDirName = process.argv[3]; | |
var database = process.argv[4]; | |
var keepTime = 7 * 24 * 3600 * 1000; //保存七天的备份 | |
function getDateString(date) { | |
if (typeof date === 'number') { | |
date = new Date(date); | |
} | |
return String(date.getFullYear()) + (date.getMonth() + 1) + date.getDate(); | |
} | |
function handleDump(now) { | |
var collectionIndex = 5; | |
var removeDir = getDateString(now.getTime() - keepTime) + '_' + baseDirName; | |
doDump(collectionIndex, now); | |
if (fs.existsSync(removeDir)) { | |
spawn('rm', ['-rf', removeDir]); | |
} | |
} | |
function doDump(index, now) { | |
var saveDir = getDateString(now) + '_' + baseDirName; | |
var dumpArgvs = ['-h', mongoHost, '-o', saveDir]; | |
if (database) { | |
dumpArgvs = dumpArgvs.concat(['-d', database]); | |
var collection = process.argv[index]; | |
if (collection) { | |
dumpArgvs = dumpArgvs.concat(['-c', collection]); | |
} | |
} | |
spawn('mongodump', dumpArgvs).on('exit', function (code) { | |
if (process.argv[++index]) { | |
doDump(index, now); | |
} | |
}); | |
} | |
setInterval(function () { | |
var now = new Date(); | |
if (now.getHours() === 3) { //凌晨三点进行备份 | |
handleDump(now); | |
} | |
}, 60 * 60 * 1000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
修改了。 可以指定数据库指定collections.