This repository has been archived by the owner on Dec 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
85 lines (71 loc) · 1.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
var which = require('which');
var exec = require('child_process').exec;
var startsWith = require('lodash.startswith');
function configure(opts, done) {
if (opts.db) return done(null, opts);
if (opts.path) {
if (
startsWith(opts.path, 'mongodb://') ||
startsWith(opts.path, 'localhost')
) {
if (!startsWith('mongodb://', opts.path)) {
opts.path = 'mongodb://' + opts.path;
}
opts.uri = opts.path;
}
}
if (opts.uri) {
opts.close_connection = true;
try {
var mongodb = require('mongodb');
} catch (e) {
console.error(
'get-mongodb-version: Failed to load MongoDB driver. Cannot lookup version by URI.',
e
);
return done(e);
}
return mongodb(opts.uri, function(err, db) {
if (err) return done(err);
opts.db = db;
done(null, opts);
});
}
if (!opts.path) {
return which('mongod', function(err, mongod_bin) {
if (err) return done(err);
if (!mongod_bin) {
return done(new Error('No mongod in path.'));
}
done(null, opts);
});
}
done(null, opts);
}
function fromPath(opts, done) {
exec(opts.path + ' --version', function(err, stdout) {
if (err) return done(err);
var shellVersion = stdout
.toString('utf-8')
.split('\n')[0]
.split(',')[0]
.replace('db version v', '');
done(null, shellVersion);
});
}
function fromDB(opts, done) {
opts.db.admin().serverInfo(function(err, res) {
if (err) return done(err);
if (opts.close_connection) {
opts.db.close();
}
done(null, res.version);
});
}
module.exports = function(opts, done) {
configure(opts, function(err, opts) {
if (err) return done(err);
if (opts.db) return fromDB(opts, done);
return fromPath(opts, done);
});
};