module.exports is the object that's actually returned as the result of a require call. Modules use exports to make things available.
The exports variable is initially set to that same object
You can create nodejs application and include below codes for package.json
{
"name": "tutorial",
"version": "1.0.0",
"scripts": {
"start": "node server.js"
}
}
Then create two js files
- hello.js
- server.js
Let is create the simplest Module
//hello.js
console.log('Hello World');
//server.js
require('./hello.js');
It is not really good way develop a module. There are some patterns on creating modules for app. (Now I will go with app.js which was server.js in last sample and foo.js which will be our modules)
Pattern 1: Define a Global
// foo.js
foo = function () {
console.log('foo!');
}
// app.js
require('./foo.js');
foo();
Global scope need to clean and nice. Pattern 01 is not much recommended
Pattern 2: Export an Anonymous Function
// foo.js
module.exports = function () {
console.log('foo!');
}
// app.js
var foo = require('./foo.js');
foo();
Pattern 3: Export an Named Function
// foo.js
exports.foo = function () {
console.log('foo!');
}
// app.js
var foo = require('./foo.js').foo;
foo();
Pattern 4: Export an Anonymous Object
// foo.js
var Foo = function () {};
Foo.prototype.log = function () {
console.log('foo!');
};
module.exports = new Foo();
// app.js
var foo = require('./foo.js');
foo.log();
Pattern 5: Export an Named Object
// foo.js
var Foo = function () {};
Foo.prototype.log = function () {
console.log('foo!');
};
exports.Foo = new Foo();
// app.js
var foo = require('./foo.js').Foo;
foo.log();
Pattern 6: Export an Anonymous Prototype
// foo.js
var Foo = function () {};
Foo.prototype.log = function () {
console.log('foo!');
}
module.exports = Foo;
// app.js
var Foo = require('./foo.js');
var foo = new Foo();
foo.log();
Pattern 7: Export an Named Prototype
// foo.js
var Foo = function () {};
Foo.prototype.log = function () {
console.log('baz!');
};
exports.Foo = Foo;
// app.js
var Foo = require('./foo.js').Foo;
var foo = new Foo();
foo.log();
No comments:
Post a Comment