Javascript – safe grauding constructor from global this
function Socket() {
if (!(this instanceof Socket)) return new Socket();
this.port = 100;
this.address = ’19.68.10.1′;
}
function Socket() {
if (!(this instanceof Socket)) return new Socket();
this.port = 100;
this.address = ’19.68.10.1′;
}
ECONNREFUSED – “Could not contact DNS servers”
ETIMEDOUT – “Timeout while contacting DNS servers / Connecting to service”
While ECONNREFUSED error will be thrown quickly upon trying create a tcp connection, ETIMEDOUT will be thrown after a default timeout period (roughly 5 minutes – measured in my code). Currently I am looking for a way to reduce this long wait before ETIMEDOUT happens. Will post soon.
Current leads…
socket.setTimeout(2 * 60 * 1000); // 2 minute timeout
socket.addListener(‘timeout’, function() {
socket.destroy();
});
https://github.com/christkv/node-mongodb-native – one of the widely used mongodb driver in node.js
Using the driver straight-way results in lot of chained callbacks and will be difficult to manage the code.
mongojs is a very nice wrapper around the driver that brings us the mongo shell like syntax to node.js.
Use db.bson.ObjectID.createPk()
It will generate a unique object id and returns for our use.
It is an alias for mongodb-native driver’s db.bson_serializer.ObjectID.createPk()
db.contacts.insert( { ‘name’ : ‘Jayyy V’, ‘gravatar’ : ‘jayyy0v’ } , cbResult );
function cbResult(err, doc) {
if (err) throw err;
else console.log(doc._id);
}
/**
*/
function UserError(message) {
Error.call(this); //super constructor
Error.captureStackTrace(this, this.constructor); //super helper method to include stack trace in error object
this.name = this.constructor.name; //set our function’s name as error name.
this.message = message; //set the error message
} UserError.prototype.__proto__ = Error.prototype;
Wrong way - stack trace will not be available
throw “invalid credentials”;
output
node.js:201
throw e; // process.nextTick error, or ‘error’ event on first tick
^
invalid credentials
Correct way – stack trace will be available
throw new Error(“invalid credentials”);
output
node.js:201
throw e; // process.nextTick error, or ‘error’ event on first tick
^
Error: invalid credentials
at Object. (/home/workspace/node/test_exception.js:4:7)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter._tickCallback (node.js:192:40)
Single Document
mongo shell provides Object.bsonsize() function to calculate the size of a document. Query the relevant document and pass it to this function.
usage
> Object.bsonsize(db.foo.findOne())
622 – output is the size in bytes
All Collections
> use <dbname>
> db.printCollectionStats()
It displays a lot metrics about each of the available collections. And “size” is one of the metric.
foo
{
“ns” : “mydb.foo”,
“count” : 21,
“size” : 4976,
“storageSize” : 15616,
“numExtents” : 1,
“nindexes” : 1,
“lastExtentSize” : 15616,
“paddingFactor” : 1,
“flags” : 1,
“totalIndexSize” : 8192,
“indexSizes” : {
“_id_” : 8192
},
“ok” : 1
}
exports vs module.exports in node.js
Here is an example of exporting a mongojs db connection from a module.
db.js
var DBConn = {
URL:’localhost:27017/mydb’
};
var collections = ['posts', 'users'];
var mydb = require(‘mongojs’).connect(DBConn.URL, collections);
module.exports = mydb;
somfile.js
var db = require(‘./db.js’); //Be sure to mention the correct relative path of db.js file. This code assumes it is in the same dir as somefile.js
db.posts.find(function(err, docs) {
console.log(docs);
});
exports vs module.exports
Although, node.js documentation says exports & module.exports are same, it is same only when you augment it.
eg. module.exports.db = mydb; or exports.db = mydb;
Now the module.exports object will look like {db:mydb} . When there is just one API/Object to be exported, doing it this way will result in a boilerplate code wherever the module is required.
require(‘./db.js’).db
To avoid this boilerplate, set the exports object to the required API/Object directly. This can be done only through module.exports
eg. module.exports = mydb; or exports = mydb; //will not work