`

Node.js Module – exports 和module.exports之间的联系与区别

 
阅读更多

来自本人论坛:www.tnodejs.com tnodejs.com

最近大家都说两者是一样的,其实不然,本文来自

http://www.hacksparrow.com/node-js-exports-vs-module-exports.html翻译
相信大家都很熟悉exports的用法了,你可以创建一个function在你的模块中如下:
exports.name = function() {
    console.log('My name is Lemmy Kilmister');
};

我们可以通过如下方法执行访问:

var rocker = require('./rocker.js');
rocker.name(); // 'My name is Lemmy Kilmister'
那么module.exports存在的意义是什么?他是否在编码中也是正确合法的?
在开源的node.js代码中可以看出,module.exports才是真正的模块export,而exports仅仅是module.exports的一个帮手。你的所有模块export的,最终都是通过module.exports返回出去的。Exports的作用主要是将所有的属性和方法整理、连接给module.exports,当module.exports还未执行。如果module.exports执行以后,所有的exports方法都将失效。
下面的例子就是说明上面一点
创建一个rocker.js:
module.exports = 'ROCK IT!';
exports.name = function() {
    console.log('My name is Lemmy Kilmister');
};
创建另外一个文件,并且执行:
var rocker = require('./rocker.js');
rocker.name(); // TypeError: Object ROCK IT! has no method 'name'
可以看到执行结果中无法获取name这个functionrocker.js中最开始就执行了module.exports,根据之前我们介绍的,在module.exports执行后他将拒绝所有的exports模块,因此我们的exports.name将会失效。从而我们无法在require模块后获取该方法。
你可能意识到,你的模块并不总是有“模块实例”。你的模块可能是任何的类型的JavaScript对象boolean, number, date, JSON, string, function, array等等。你可以通过module.exports任何的对象。
If you don't set module.exports to anythingexplicitly, the properties of exports and attached to it and returned.
In this case, your module is a class:
module.exports = function(name, age) {
    this.name = name;
    this.age = age;
    this.about = function() {
        console.log(this.name +' is '+ this.age +' years old');
    };
};
and you'd use it this way:
var Rocker = require('./rocker.js');
var r = new Rocker('Ozzy', 62);
r.about(); // Ozzy is 62 years old
In this case, your module is an array:
module.exports = ['Lemmy Kilmister', 'Ozzy Osbourne', 'Ronnie James Dio', 'Steven Tyler', 'Mick Jagger'];
and you may use it this way:
var rocker = require('./rocker.js');
console.log('Rockin in heaven: ' + rocker[2]); //Rockin in heaven: Ronnie James Dio
So you get the point now - if you want yourmodule to be of a specific object type, use module.exports; if you want yourmodule to be a typical module instance, use exports.
The result of attaching properties tomodule.exports is akin to attaching properties to exports. For example this:
module.exports.name = function() {
    console.log('My name is Lemmy Kilmister');
};
does the same thing as:
exports.name = function() {
    console.log('My name is Lemmy Kilmister');
};
But note that, they are not the same thing.As I said earlier module.exports is the real deal, exports is just its littlehelper. Having said that, exports is the recommended object unless you areplanning to change the object type of your module from the traditional 'module instance'to something else.
I hope this post helped you understand thedifference between exports and module.exports, and learn a bit more about howmodules work in Node.js. Any questions, ping me in the comments.
加上官网的介绍
The exports object is created by the Modulesystem. Sometimes this is not acceptable, many want their module to be aninstance of some class. To do this assign the desired export object to module.exports. For example suppose we were making amodule called a.js
var EventEmitter = require('events').EventEmitter;
module.exports = new EventEmitter();
// Do some work, and after some time emit
// the 'ready' event from the module itself.
setTimeout(function() {
  module.exports.emit('ready');
}, 1000);
Then in another file we could do
var a = require('./a');
a.on('ready', function() {
  console.log('module a is ready');
});
Note that assignment to [font='Lucida Console']module.exports must be done immediately. It cannotbe done in any callbacks. This does not work:
x.js:
setTimeout(function() {
  module.exports = { a: "hello" };
}, 0);
y.js:
var x = require('./x');
console.log(x.a);

分享到:
评论

相关推荐

    pubdreamcc#Node.js#06.Node.js中module.exports和exports的区别1

    前言Node中,每个模块都有一个exports接口对象,我们需要把公共的方法或者字符串挂载在这个接口对象中,其他的模块才可以使用。Node.js中只有模块作用域

    node.js中module.exports与exports用法上的区别

    Node.js 引入了模块(Module)概念,一个模块可以通过module.exports 或 exports 将函数、变量等导出,以使其它 JavaScript 脚本通过require() 函数引入并使用。  module.exports 初始值为一个空对象 {},所以 ...

    详解Node.js中exports和module.exports的区别

    今天看了下node.js的require方法的源码,终于搞清楚exports和module.exports的区别了。 我们知道,node.js的模块暴露有两种方法。 1. 方式一:用exports //a.js exports.log =function (str) { console.log(str)...

    Node.js 中exports 和 module.exports 的区别

    主要介绍了Node.js 中exports 和 module.exports 的区别的相关资料,需要的朋友可以参考下

    node.js的exports、module.exports与ES6的export、export default深入详解

    module.exports / exports: 只有 node 支持的导出 这一刻起,我觉得是时候要把它们之间的关系都给捋清楚了,不然我得混乱死。话不多少,咱们开干!! node模块 Node里面的模块系统遵循的是Com

    node.js中module模块的功能理解与用法实例分析

    本文实例讲述了node.js中module模块的功能理解与用法。分享给大家供大家参考,具体如下: node.js中使用CommonJS规范实现模块功能,一个单独的文件就是一个单独的模块。通过require方法实现模块间的依赖管理。 通过...

    深入理解node exports和module.exports区别

    我们只需知道三点即可知道 exports 和 module.exports 的区别了: 1.exports 是指向的 module.exports 的引用 2.module.exports 初始值为一个空对象 {},所以 exports 初始值也是 {} 3.require() 返回的是 module....

    一起学 Node.js

    exports 和 module.exports Promise 环境变量 packge.json semver npm 使用注意事项 npm init npm install npm scripts npm shrinkwrap Hello, Express 初始化一个 Express 项目 supervisor 路由 express.Router ...

    node.js封装的一个MongoDB操作类库

    基于node封装的一个MongoDB操作类库 包括增删改查 分页查询 批量操作 采用单例模式大大提高性能 使用时需新建一个config.js配置数据库地址 数据库名称 const Config ={ ...module.exports = Config;

    Node.js: JavaScript based framework. Easy Guide Book

    Node.js: JavaScript based framework. Easy Guide Book by Rick L. English | April 13, 2016 | ASIN: B01E8KVNVW | 75 Pages | AZW3/MOBI/EPUB/PDF The following topics are discussed in this book:  A ...

    DynamoDB的Node.jsORM框架Dynasaur.zip

    Dynasaur 是 Node.js 的一个 ORM 扩展框架,用来访问 AWS 的 DynamoDB NoSQL 数据库。 示例代码: module.exports = (dynasaur) -> blog_post_schema = attributes: author: String title: String body...

    Node.js的DAO框架bearcat-dao.zip

    概述bearcat-dao 是一个 node.js 基于 SQL mapping 的 DAO 框架。实现了基于 SQL mapping 来对数据结果集进行映射,是一种半自动化的模式,相比较于 O/R mapping 全自动化的模式。 因此,在 bearcat-dao 里,开发者...

    详解Sea.js中Module.exports和exports的区别

    因为SeaJs和Nodejs都是基于CommonJS,所以直接看的Node的官方文档解释 Module.exports The module.exports object is created by the Module system. Sometimes this is not acceptable; many want their module to ...

    Node.js模块化加载Browserify.zip

    Browserify 可以让你使用类似于 node 的 require() 的方式来组织浏览器端的 Javascript 代码,通过预编译让前端 Javascript 可以直接使用 Node NPM 安装的一些库。 安装: npm install -g browserify 示例 这是 ...

    eos的Node.js开发包node-eos.zip

    node-eos 是 eos 的 Node.js 客户端开发包。 init eos : var eos = require("node-eos"); eos.init({  zookeeper_ip: '192.168.0.224',  zookeeper_port: 2181,  long_connect: true,  exclude_eos:[],//...

Global site tag (gtag.js) - Google Analytics