NODEJS(10)Book Read - hands-on-nodejs.pdf - pseudo class

NODEJS(10)Book Read - hands-on-nodejs.pdf - pseudo class

3. Making Modules
A pseudo-class
var Line = function(x1, y1, x2, y2) {
     this.x1 = x1;
     this.y1 = y1;
     this.x2 = x2;
     this.y2 = y2;   
};

Line.prototype.length = function() {
     return Math.sqrt(
          Math.pow(Math.abs(this.x1 - this.x2),2) +
          Math.pow(Math.abs(this.y1 - this.y2),2)
     );
};

module.exports.create = function(x1, y1, x2, y2) {
     return new Line(x1, y1, x2, y2);
};

That is a pseudo-class which named Line, when we use it we can do like this,
var Line = require(‘./line’);
var line = Line.create(2,4,10,15);
console.log(‘this line length is ‘ + line.length());

A psedo-class that inherits
var util = require(‘util’);
var EventEmitter = require(‘events’).EventEmitter;

var Line = function(x1, y1, x2, y2) {
     …snip...
};

util.inherits(Line, EventEmitter);

Line.prototype.length = function() {
     …snip...
};

node_modules and NPM bundle

I can commit my modules to git, and then, who plan to use it can do like this.

For example, this is for the tool AES, package.json
{
     "name"               :     "sillycat-aes",
     "version"          :     "0.1.0",
     "description"     :     "Module for AES encryption and descritpion",
     "main"               :      "lib/app.js"
}

When we plan to use it, we do like this, package.json
{
     "name"               :     "sillycat-platform",
     "version"          :     "0.1.0",
     "description"     :     "Sillycat Platform, provide all kinds of tools.",
     "main"               :      "lib/app.js",
     "dependencies"     :     {
          "sillycat-aes"     :     "git://github.com/luohuazju/sillycat-aes.git"
     }
}

Just use NPM command to install that.
>npm install


References:
package.json
http://docs.spmjs.org/doc/package
http://blog.uifanr.com/2013/03/13/478
http://blog.csdn.net/zimin1985/article/details/18958741


你可能感兴趣的:(nodejs)