Sunday, March 15, 2015

Codeschool: Real Time Web, Part II

Modules

Suppose we created a module called custom_hello.js:

var hello = function(){
  console.log("hello!");
}
module.exports = hello;
then to use this in another file, we write
var h = require('./custom_hello');
h.hello();
Shorthand notation:
exports.hello = function(){
  console.log("hello!");
}
and correspondingly, to use.
require('./custom_hello').hello();
In this way, you can actually choose which functions to export.
var foo1 = function() { ... }
var foo2 = function() { ... }
module.exports.foo1 = foo1
which makes foo2 a private function.

npm

npm is the package manager for node. You can find repositories of modules in http://www.npmjs.org. To install a module, use

$ npm install 
which is going to install said module in node_modules directory in your application root.

It is also a good idea to have package.json in your app root directory, which contains the dependencies your app needs, for example
{
  "name": "My App",
  "version" : "1",
  "dependencies": {
    "connect": "1.8.7" 
  }
}
Running npm install will install all the dependencies. Each dependency may of course has its own dependencies, i.e. its own package.json file.

No comments:

Post a Comment