nodejs的exports解读

nodejs模块之间的引用,都通过exports/module.exports来导出,导出是什么格式呢?

我们看以下代码:index.js导出几个function,每一个function/class都在不同的文件里。

//index.js
exports.HttpClient = require('./http');
exports.SocketClient = require('./socket');
exports.isMessageType = require('./message').isMessageType;
exports.createMessage = require('./message').createMessage;
//http.js
....
module.exports = HttpClient;
//demo.js
const  Mixin-node-client  = require('mixin-node-client');
console.log(Mixin-node-client);

上面的demo.js引用index.js定义的类,我们看看demo.js输出是什么:

wenewzha:examples wenewzhang$ node http.js
{ HttpClient: [Function: HttpClient],
  SocketClient: [Function: SocketClient],
  isMessageType: [Function: isMessageType],
  createMessage: [Function: createMessage] }

由此可见,exports输出就是一个类。

如果我们只需要导入一个HttpClient应该怎么用?

const { HttpClient }  = require('mixin-node-client');

https://github.com/wangshijun/mixin-node-client/

Tags

添加新评论

Restricted HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。