Created
September 12, 2017 14:50
-
-
Save etissieres/0fa2948c31f17eba5d19e2b433e3d4d2 to your computer and use it in GitHub Desktop.
Old repo, no more used
This file contains hidden or 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
#!/usr/bin/env node | |
var commander = require('commander'); | |
var mongo = require('mongodb'); | |
var moment = require('moment'); | |
commander | |
.version(require('./package').version) | |
.option('-d, --database <str>', 'Database name') | |
.option('-c, --collection <str>', 'Collection name') | |
.option('-s, --host [str]', 'Host') | |
.option('-p, --port [n]', 'Port', parseInt) | |
.option('-i, --interval [n]', 'Count interval (ms)', parseInt) | |
.option('-n, --number [n]', 'Count number', parseInt) | |
.option('-q, --query [path]', 'Query json file') | |
.parse(process.argv); | |
var conf = { | |
mongo: { | |
host: commander.host || '127.0.0.1', | |
port: commander.port || mongo.Connection.DEFAULT_PORT, | |
dbname: commander.database, | |
collection: commander.collection | |
}, | |
interval: commander.interval || 1000, | |
number: commander.number || 0, | |
query: '' | |
}; | |
/* configuration check */ | |
if (!conf.mongo.dbname || !conf.mongo.collection) { | |
console.error('> Missing database or collection !', conf.mongo); | |
process.exit(1); | |
} | |
if (commander.query) { | |
try { | |
conf.query = require(securePath(commander.query)); | |
} catch (err) { | |
console.error('> Cannot use specified query (' + commander.query + ')', err); | |
} | |
} | |
console.log('> Using configuration', conf); | |
/* main */ | |
var server = new mongo.Server(conf.mongo.host, conf.mongo.port, {'auto_reconnect': true}); | |
var client = new mongo.MongoClient(server); | |
client.open(function (err, client) { | |
if (err) { | |
console.error('> Cant connect database', err); | |
process.exit(1); | |
} | |
console.log('> Connected to database'); | |
var db = client.db(conf.mongo.dbname); | |
var collection = db.collection(conf.mongo.collection); | |
var n = 0; | |
(function tick() { | |
collection.count(conf.query, function (err, count) { | |
if (err) { | |
return console.error('> error retreiving count', err); | |
} | |
console.log('[' + moment().format('YYYY-MM-DD HH:mm:ss') + ']', count); | |
if (++n !== conf.number) { | |
setTimeout(tick, conf.interval); | |
} else { | |
db.close(); | |
} | |
}); | |
})(); | |
}); | |
/* utils */ | |
function securePath(path) { | |
if (path.indexOf('/') !== 0 && path.indexOf('./') !== 0 && path.indexOf('../') !== 0) { | |
path = './' + path; | |
} | |
return path; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment