06.07.2017 Views

Mastering JavaScript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Server-Side <strong>JavaScript</strong><br />

The geo module created earlier in this section can be rewritten in order to return a<br />

single Geo constructor function rather than an object containing functions. We can<br />

rewrite the geo module and its usage as follows:<br />

var Geo = function(PI) {<br />

this.PI = PI;<br />

}<br />

Geo.prototype.area = function (r) {<br />

return this.PI * r * r;<br />

};<br />

Geo.prototype.circumference = function (r) {<br />

return this.PI * this.PI * r;<br />

};<br />

module.exports = Geo;<br />

Consider a config.js module:<br />

var db_config = {<br />

server: "0.0.0.0",<br />

port: "3306",<br />

user: "mysql",<br />

password: "mysql"<br />

};<br />

module.exports = db_config;<br />

If you want to access db_config from outside this module, you can use require()<br />

to include the module and refer the object as follows:<br />

var config = require('./config.js');<br />

console.log(config.user);<br />

There are three ways to organize modules:<br />

• Using a relative path, for example, config = require('./lib/config.<br />

js')<br />

• Using an absolute path, for example, config = require('/nodeproject/<br />

lib/config.js')<br />

• Using a module search, for example, config = require('config')<br />

The first two are self-explanatory—they allow Node to look for a module in a<br />

particular location in the filesystem.<br />

[ 214 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!