Click here to Skip to main content
12,399,281 members (57,867 online)
Click here to Skip to main content
Articles » Web Development » Node.js » General » Downloads

Stats

146.1K views
2K downloads
160 bookmarked
Posted

Node.Js And Stuff

, 11 Feb 2013 CPOL
Small demo app using Node.Js/Socket.IO/MongoDB/D3.Js and jQuery.
WebSocketDemo
node_modules
.bin
express
.npmignore
.travis.yml
History.md
lib
router
node_modules
commander
.npmignore
.travis.yml
History.md
lib
Readme.md
connect
.npmignore
lib
middleware
session
public
favicon.ico
icons
page.png
page_add.png
page_attach.png
page_code.png
page_copy.png
page_delete.png
page_edit.png
page_error.png
page_excel.png
page_find.png
page_gear.png
page_go.png
page_green.png
page_key.png
page_lightning.png
page_link.png
page_paintbrush.png
page_paste.png
page_red.png
page_refresh.png
page_save.png
page_white.png
page_white_acrobat.png
page_white_actionscript.png
page_white_add.png
page_white_c.png
page_white_camera.png
page_white_cd.png
page_white_code.png
page_white_code_red.png
page_white_coldfusion.png
page_white_compressed.png
page_white_copy.png
page_white_cplusplus.png
page_white_csharp.png
page_white_cup.png
page_white_database.png
page_white_delete.png
page_white_dvd.png
page_white_edit.png
page_white_error.png
page_white_excel.png
page_white_find.png
page_white_flash.png
page_white_freehand.png
page_white_gear.png
page_white_get.png
page_white_go.png
page_white_h.png
page_white_horizontal.png
page_white_key.png
page_white_lightning.png
page_white_link.png
page_white_magnify.png
page_white_medal.png
page_white_office.png
page_white_paint.png
page_white_paintbrush.png
page_white_paste.png
page_white_php.png
page_white_picture.png
page_white_powerpoint.png
page_white_put.png
page_white_ruby.png
page_white_stack.png
page_white_star.png
page_white_swoosh.png
page_white_text.png
page_white_text_width.png
page_white_tux.png
page_white_vector.png
page_white_visualstudio.png
page_white_width.png
page_white_word.png
page_white_world.png
page_white_wrench.png
page_white_zip.png
page_word.png
page_world.png
node_modules
bytes
.npmignore
History.md
Readme.md
formidable
.npmignore
.travis.yml
benchmark
example
lib
node-gently
example
lib
gently
Readme.md
test
simple
Readme.md
test
fixture
file
http
special-chars-in-filename
info.md
js
integration
legacy
integration
simple
system
unit
tool
pause
.npmignore
History.md
Readme.md
qs
.gitmodules
.npmignore
.travis.yml
History.md
lib
Readme.md
test
mocha.opts
Readme.md
cookie
.npmignore
.travis.yml
README.md
test
mocha.opts
crc
.gitmodules
.npmignore
lib
README.md
test
debug
.npmignore
example
History.md
lib
Readme.md
fresh
.npmignore
Readme.md
methods
mkdirp
.gitignore.orig
.gitignore.rej
.npmignore
.travis.yml
examples
pow.js.orig
pow.js.rej
README.markdown
test
range-parser
.npmignore
History.md
Readme.md
send
.npmignore
History.md
lib
node_modules
mime
README.md
types
mime.types
node.types
Readme.md
Readme.md
jade
.npmignore
jade.md
lib
nodes
node_modules
commander
.npmignore
.travis.yml
History.md
lib
Readme.md
mkdirp
.npmignore
.travis.yml
examples
README.markdown
test
Readme.md
test.jade
testing
head.jade
index.jade
layout.jade
user.jade
mongodb
.travis.yml
CONTRIBUTING.md
lib
mongodb
commands
connection
strategies
gridfs
responses
node_modules
bson
.travis.yml
benchmarks
binding.gyp
build
binding.Makefile
bson.target.mk
config.gypi
Release
.deps
Release
bson.node.d
obj.target
bson
ext
bson.o.d
bson.node
linker.lock
obj.target
bson
ext
bson.o
ext
bson.cc
win32
ia32
bson.node
x64
bson.node
lib
bson
README.md
test
browser
node
data
test_gs_weird_bug.png
tools
tools
jasmine-1.1.0
jasmine_favicon.png
MIT.LICENSE
Readme.md
node-static
.npmignore
benchmark
bin
etc
trainwreck.jpg
examples
lib
node-static
node_modules
colors
ReadMe.md
optimist
.travis.yml
example
node_modules
wordwrap
.npmignore
example
README.markdown
test
README.markdown
test
_
README.md
test
fixtures
integration
socket.io
.npmignore
.travis.yml
benchmarks
History.md
lib
stores
transports
websocket
node_modules
policyfile
.npmignore
doc
examples
lib
README.md
tests
ssl
ssl.crt
ssl.private.key
redis
.npmignore
benches
stress
pubsub
rpushblpop
speed
size-rate.png
changelog.md
examples
lib
parser
README.md
socket.io-client
.npmignore
bin
dist
WebSocketMain.swf
WebSocketMainInsecure.swf
History.md
lib
transports
vendor
web-socket-js
.npmignore
flash-src
build.sh
com
adobe
net
proxies
RFC2817Socket.as
gsolo
encryption
MD5.as
hurlant
crypto
cert
MozillaRootCertificates.as
X509Certificate.as
X509CertificateCollection.as
Crypto.as
hash
HMAC.as
IHash.as
IHMAC.as
MAC.as
MD2.as
MD5.as
SHA1.as
SHA224.as
SHA256.as
SHABase.as
prng
ARC4.as
IPRNG.as
Random.as
TLSPRF.as
rsa
RSAKey.as
symmetric
AESKey.as
aeskey.pl
BlowFishKey.as
CBCMode.as
CFB8Mode.as
CFBMode.as
CTRMode.as
DESKey.as
ECBMode.as
ICipher.as
IMode.as
IPad.as
IStreamCipher.as
ISymmetricKey.as
IVMode.as
NullPad.as
OFBMode.as
PKCS5.as
SimpleIVMode.as
SSLPad.as
TLSPad.as
TripleDESKey.as
XTeaKey.as
tests
AESKeyTest.as
ARC4Test.as
BigIntegerTest.as
BlowFishKeyTest.as
CBCModeTest.as
CFB8ModeTest.as
CFBModeTest.as
CTRModeTest.as
DESKeyTest.as
ECBModeTest.as
HMACTest.as
ITestHarness.as
MD2Test.as
MD5Test.as
OFBModeTest.as
RSAKeyTest.as
SHA1Test.as
SHA224Test.as
SHA256Test.as
TestCase.as
TLSPRFTest.as
TripleDESKeyTest.as
XTeaKeyTest.as
tls
BulkCiphers.as
CipherSuites.as
IConnectionState.as
ISecurityParameters.as
KeyExchanges.as
MACs.as
SSLConnectionState.as
SSLEvent.as
SSLSecurityParameters.as
TLSConfig.as
TLSConnectionState.as
TLSEngine.as
TLSError.as
TLSEvent.as
TLSSecurityParameters.as
TLSSocket.as
TLSSocketEvent.as
TLSTest.as
math
BarrettReduction.as
bi_internal.as
BigInteger.as
ClassicReduction.as
IReduction.as
MontgomeryReduction.as
NullReduction.as
util
ArrayUtil.as
Base64.as
der
ByteString.as
DER.as
IAsn1Type.as
Integer.as
ObjectIdentifier.as
OID.as
PEM.as
PrintableString.as
Sequence.as
Set.as
Type.as
UTCTime.as
Hex.as
Memory.as
IWebSocketLogger.as
WebSocket.as
WebSocketEvent.as
WebSocketMain.as
WebSocketMainInsecure.as
README.md
WebSocketMain.swf
WebSocketMainInsecure.zip
node_modules
.bin
active-x-obfuscator
.npmignore
node_modules
zeparser
.npmignore
Readme.md
uglify-js
.npmignore
lib
package.json~
README.org
test
unit
compress
expected
test
tmp
ws
.npmignore
.travis.yml
bench
binding.gyp
doc
ws.md
examples
fileapi
.npmignore
public
serverstats
public
serverstats-express_3
public
History.md
lib
node_modules
commander
.npmignore
.travis.yml
History.md
lib
Readme.md
options
.npmignore
lib
README.md
test
fixtures
test.conf
tinycolor
.npmignore
README.md
README.md
src
bufferutil.cc
validation.cc
test
fixtures
certificate.pem
key.pem
request.pem
xmlhttprequest
autotest.watchr
example
lib
README.md
tests
README.md
test
node
Readme.md
stylus
lib
convert
functions
index.styl
nodes
stack
visitor
node_modules
cssom
.gitmodules
.npmignore
lib
README.mdown
debug
.npmignore
example
History.md
lib
Readme.md
mkdirp
.npmignore
.travis.yml
examples
README.markdown
test
Readme.md
testing
small.styl
test.styl
public
images
Friend.png
Header.pdn
Header.png
javascripts
jquery-ui-1.9.1.custom
css
ui-lightness
images
ui-bg_diagonals-thick_18_b81900_40x40.png
ui-bg_diagonals-thick_20_666666_40x40.png
ui-bg_flat_10_000000_40x100.png
ui-bg_glass_100_f6f6f6_1x400.png
ui-bg_glass_100_fdf5ce_1x400.png
ui-bg_glass_65_ffffff_1x400.png
ui-bg_gloss-wave_35_f6a828_500x100.png
ui-bg_highlight-soft_100_eeeeee_1x100.png
ui-bg_highlight-soft_75_ffe45c_1x100.png
ui-icons_222222_256x240.png
ui-icons_228ef1_256x240.png
ui-icons_ef8c08_256x240.png
ui-icons_ffd27a_256x240.png
ui-icons_ffffff_256x240.png
js
stylesheets
home.styl
style.styl
routes
views
d3demo.jade
home.jade
layout.jade
/*!
 * Module dependencies.
 */
var Collection = require('./collection').Collection,
    Cursor = require('./cursor').Cursor,
    DbCommand = require('./commands/db_command').DbCommand;

/**
 * Allows the user to access the admin functionality of MongoDB
 *
 * @class Represents the Admin methods of MongoDB.
 * @param {Object} db Current db instance we wish to perform Admin operations on.
 * @return {Function} Constructor for Admin type.
 */
function Admin(db) {
  if(!(this instanceof Admin)) return new Admin(db);
  this.db = db;
};

/**
 * Retrieve the server information for the current
 * instance of the db client
 *
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from buildInfo or null if an error occured.
 * @return {null} Returns no result
 * @api public
 */
Admin.prototype.buildInfo = function(callback) {
  this.serverInfo(callback);
}

/**
 * Retrieve the server information for the current
 * instance of the db client
 *
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from serverInfo or null if an error occured.
 * @return {null} Returns no result
 * @api private
 */
Admin.prototype.serverInfo = function(callback) {
  this.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) {
    if(err != null) return callback(err, null);
    return callback(null, doc.documents[0]);
  });
}

/**
 * Retrieve this db's server status.
 *
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from serverStatus or null if an error occured.
 * @return {null}
 * @api public
 */
Admin.prototype.serverStatus = function(callback) {
  var self = this;

  this.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) {
    if(err == null && doc.documents[0].ok === 1) {
      callback(null, doc.documents[0]);
    } else {
      if(err) return callback(err, false);
      return callback(self.db.wrap(doc.documents[0]), false);
    }
  });
};

/**
 * Retrieve the current profiling Level for MongoDB
 *
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from profilingLevel or null if an error occured.
 * @return {null} Returns no result
 * @api public
 */
Admin.prototype.profilingLevel = function(callback) {
  var self = this;

  this.db.executeDbAdminCommand({profile:-1}, function(err, doc) {
    doc = doc.documents[0];

    if(err == null && doc.ok === 1) {
      var was = doc.was;
      if(was == 0) return callback(null, "off");
      if(was == 1) return callback(null, "slow_only");
      if(was == 2) return callback(null, "all");
        return callback(new Error("Error: illegal profiling level value " + was), null);
    } else {
      err != null ? callback(err, null) : callback(new Error("Error with profile command"), null);
    }
  });
};

/**
 * Ping the MongoDB server and retrieve results
 *
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from ping or null if an error occured.
 * @return {null} Returns no result
 * @api public
 */
Admin.prototype.ping = function(options, callback) {
  // Unpack calls
  var args = Array.prototype.slice.call(arguments, 0);
  callback = args.pop();

  this.db.executeDbAdminCommand({ping: 1}, callback);
}

/**
 * Authenticate against MongoDB
 *
 * @param {String} username The user name for the authentication.
 * @param {String} password The password for the authentication.
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from authenticate or null if an error occured.
 * @return {null} Returns no result
 * @api public
 */
Admin.prototype.authenticate = function(username, password, callback) {
  this.db.authenticate(username, password, {authdb: 'admin'}, function(err, doc) {
    return callback(err, doc);
  })
}

/**
 * Logout current authenticated user
 *
 * @param {Object} [options] Optional parameters to the command.
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from logout or null if an error occured.
 * @return {null} Returns no result
 * @api public
 */
Admin.prototype.logout = function(callback) {
  this.db.logout({authdb: 'admin'},  function(err, doc) {
    return callback(err, doc);
  })
}

/**
 * Add a user to the MongoDB server, if the user exists it will
 * overwrite the current password
 *
 * Options
 *  - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
 *
 * @param {String} username The user name for the authentication.
 * @param {String} password The password for the authentication.
 * @param {Object} [options] additional options during update.
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from addUser or null if an error occured.
 * @return {null} Returns no result
 * @api public
 */
Admin.prototype.addUser = function(username, password, options, callback) {
  var args = Array.prototype.slice.call(arguments, 2);
  callback = args.pop();
  options = args.length ? args.shift() : {};

  options.dbName = 'admin';
  // Add user
  this.db.addUser(username, password, options, function(err, doc) {
    return callback(err, doc);
  })
}

/**
 * Remove a user from the MongoDB server
 *
 * Options
 *  - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
 *
 * @param {String} username The user name for the authentication.
 * @param {Object} [options] additional options during update.
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from removeUser or null if an error occured.
 * @return {null} Returns no result
 * @api public
 */
Admin.prototype.removeUser = function(username, options, callback) {
  var self = this;
  var args = Array.prototype.slice.call(arguments, 1);
  callback = args.pop();
  options = args.length ? args.shift() : {};
  options.dbName = 'admin';

  this.db.removeUser(username, options, function(err, doc) {
    return callback(err, doc);
  })
}

/**
 * Set the current profiling level of MongoDB
 *
 * @param {String} level The new profiling level (off, slow_only, all)
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from setProfilingLevel or null if an error occured.
 * @return {null} Returns no result
 * @api public
 */
Admin.prototype.setProfilingLevel = function(level, callback) {
  var self = this;
  var command = {};
  var profile = 0;

  if(level == "off") {
    profile = 0;
  } else if(level == "slow_only") {
    profile = 1;
  } else if(level == "all") {
    profile = 2;
  } else {
    return callback(new Error("Error: illegal profiling level value " + level));
  }

  // Set up the profile number
  command['profile'] = profile;

  this.db.executeDbAdminCommand(command, function(err, doc) {
    doc = doc.documents[0];

    if(err == null && doc.ok === 1)
      return callback(null, level);
    return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null);
  });
};

/**
 * Retrive the current profiling information for MongoDB
 *
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from profilingInfo or null if an error occured.
 * @return {null} Returns no result
 * @api public
 */
Admin.prototype.profilingInfo = function(callback) {
  try {
    new Cursor(this.db, new Collection(this.db, DbCommand.SYSTEM_PROFILE_COLLECTION), {}, {}, {dbName: 'admin'}).toArray(function(err, items) {
        return callback(err, items);
    });
  } catch (err) {
    return callback(err, null);
  }
};

/**
 * Execute a db command against the Admin database
 *
 * @param {Object} command A command object `{ping:1}`.
 * @param {Object} [options] Optional parameters to the command.
 * @param {Function} callback this will be called after executing this method. The command always return the whole result of the command as the second parameter.
 * @return {null} Returns no result
 * @api public
 */
Admin.prototype.command = function(command, options, callback) {
  var self = this;
  var args = Array.prototype.slice.call(arguments, 1);
  callback = args.pop();
  options = args.length ? args.shift() : {};

  // Execute a command
  this.db.executeDbAdminCommand(command, options, function(err, doc) {
    // Ensure change before event loop executes
    return callback != null ? callback(err, doc) : null;
  });
}

/**
 * Validate an existing collection
 *
 * @param {String} collectionName The name of the collection to validate.
 * @param {Object} [options] Optional parameters to the command.
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from validateCollection or null if an error occured.
 * @return {null} Returns no result
 * @api public
 */
Admin.prototype.validateCollection = function(collectionName, options, callback) {
  var args = Array.prototype.slice.call(arguments, 1);
  callback = args.pop();
  options = args.length ? args.shift() : {};

  var self = this;
  var command = {validate: collectionName};
  var keys = Object.keys(options);

  // Decorate command with extra options
  for(var i = 0; i < keys.length; i++) {
    if(options.hasOwnProperty(keys[i])) {
      command[keys[i]] = options[keys[i]];
    }
  }

  this.db.executeDbCommand(command, function(err, doc) {
    if(err != null) return callback(err, null);
    doc = doc.documents[0];

    if(doc.ok === 0)
      return callback(new Error("Error with validate command"), null);
    if(doc.result != null && doc.result.constructor != String)
      return callback(new Error("Error with validation data"), null);
    if(doc.result != null && doc.result.match(/exception|corrupt/) != null)
      return callback(new Error("Error: invalid collection " + collectionName), null);
    if(doc.valid != null && !doc.valid)
      return callback(new Error("Error: invalid collection " + collectionName), null);

    return callback(null, doc);
  });
};

/**
 * List the available databases
 *
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from listDatabases or null if an error occured.
 * @return {null} Returns no result
 * @api public
 */
Admin.prototype.listDatabases = function(callback) {
  // Execute the listAllDatabases command
  this.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, doc) {
    if(err != null) return callback(err, null);
    return callback(null, doc.documents[0]);
  });
}

/**
 * Get ReplicaSet status
 *
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from replSetGetStatus or null if an error occured.
 * @return {null}
 * @api public
 */
Admin.prototype.replSetGetStatus = function(callback) {
  var self = this;

  this.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) {
    if(err == null && doc.documents[0].ok === 1)
      return callback(null, doc.documents[0]);
    if(err) return callback(err, false);
    return callback(self.db.wrap(doc.documents[0]), false);
  });
};

/**
 * @ignore
 */
exports.Admin = Admin;

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sacha Barber
Software Developer (Senior)
United Kingdom United Kingdom
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.

Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2016
  • Codeproject MVP 2016
  • Microsoft C# MVP 2015
  • Codeproject MVP 2015
  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 11 Feb 2013
Article Copyright 2013 by Sacha Barber
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid