As I am new to Node.js I am looking for some info, coding some testing stuff and also reading some other people's code.
I've seen that creating/requiring(using) modules is typical in Node.js. I've seen different ways of defining "public" methods and function inside modules and both seem to work the same way too:
module.exportsthis.prototypeIs there a notable difference by using one or another? Or are just different ways of doing the same thing? Is any of these two better, or it depends on the context?
You should use either exports to attach properties to the predefined exported object or reassign module.exports to your own object. The latter is common when exporting a constructor for example.
exports.foo = function() { console.log('Hello world!'); };
exports.add = function(a, b) { return a + b; };
// Then the module might be used like so:
// var mymodule = require('./mymodule');
// mymodule.foo();
// console.log(mymodule.add(1, 9));
Or replace the exports object:
function Foo() {
}
module.exports = Foo;
// then typically users do this in their script:
// var Foo = require('./mymodule');
// var myFoo = new Foo();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With