-
Notifications
You must be signed in to change notification settings - Fork 11
Node.js "Tricks of Trade"
&here some of the trick is use. if you have some, please add them here.
##Async JavaScript programming In node.js everything is asynchronous to be successful you need to use some javascript library. for example: http://github.com/shimondoodkin/node-inflow
##New scope creation function call: //current scope (function (arg){ //new scope })("foo");
##Include files. In node.js theres no include files, a solution could be to have an object of you application and extend it with in the included file. also when you require the include file it has no access to parent variables you are working with here is an idea for a solution to start you get going:
version 1:
----app.js---- var app={}; require('./app_somefunctions').main(app);
----app_somefunctions.js---- this.main=function(app) { app.somefunction1=function(){ return "foo"; } app.somefunction2=function(){ return "bar"; } }
version 2:
----app.js---- var app={}; var param2="pam param pararam"; require('./app_somefunctions').main.call(app);
----app_somefunctions.js---- this.main=function() { this.somefunction1=function(){ return "foo"; } this.somefunction2=function(){ return "bar"; } }
// function.call(new_this,arg1,arg2...) // call a function with an other "this"
// function.apply(new_this,[arg1,arg2]) // the difference is apply receives arguments as an array
the difference between the two versions is in version1 an object name is used in version2 "this" is used. by the way this is the same way the native module.require function is done in node js.
##Short use of require:
console.log(require('sys').inspect(...));
##Make it not crush, How to print a call stack add on error error handler, and also print the call stack. in my apps i assign this event only after a successful load.
process.on('error', function (err) {
console.log(err.stack);
});
function aaa(i)
{
if(i<0) throw new Error("i<0");
}
try{
aaa(-1);
}catch(e){
console.log(e.stack);
}
try{
throw new Error("Trace");
}catch(e){
console.log(e.stack);
}
##links: http://sweatte.wordpress.com/syntax/javascript-idioms-and-gotchas/ - learn functions http://www.herongyang.com/JavaScript/About-This-JavaScript-Tutorial-Example-Book.html - learn javascript in general