The reference to the module is a very important part of the backend language, so how do you do that in Nodejs?
When referencing other modules, there are two common methods: Exports,module.exports.
Next, we'll write a demo to tell the difference.
Testmodule.js:
function User (name,title,post) { this. name=name; this. title=title; this. post=function() { console.log (' hello ' +this. name);}; Module.exports=user;
Testexports.js:
exports.sayhello=function(name) { console.log (' Hello, ' +name);}
Test.js:
var testmodule=require ('./testmodule '); Console.log (typeofvar newtestobj=New testmodule (' Mike ', ' Zhejiang ', ' 311301 '); Console.log(typeof( Newtestobj)); var testexports=require ('./testexports '); Console.log (testexports);
Run the Test.js and output in turn:
function
Object
{sayhello: [Function]}
It is obvious that Module.exports is actually returning a constructor, and exports only returns an object.
Nodejs Module Reference