1.nodejs暴露方法

如果要对外暴露属性或方法,就用 exports 就行,要暴露对象(类似class,包含了很多属性和方法),就用 module.exports

1.简单的暴露属性和方法

  1. exports.world = function() {
  2. console.log('Hello World');
  3. }

2.暴露对象的方法

  1. //hello.js
  2. function Hello() {
  3. var name;
  4. this.setName = function(thyName) {
  5. name = thyName;
  6. };
  7. this.sayHello = function() {
  8. console.log('Hello ' + name);
  9. };
  10. };
  11. module.exports = Hello;
  12. //main.js
  13. //调用Hello类
  14. var Hello = require('./hello');
  15. hello = new Hello();
  16. hello.setName('BYVoid');
  17. hello.sayHello();