Node.js 之基于文件的模块系统

Node.js 之基于文件的模块系统

 
/**
 * 
 *
 *
 * Kevin Dongaoor created CommonJS in 2009 with the goal to specify an ecosystem
 * for JavaScript modules on the server. Node.js follows the CommonJS module
 * specification. Following are a few salient points of the module system: •
 * Each file is its own module. • Each file has access to the current module
 * definition using the module variable. • The export of the current module is
 * determined by the module.exports variable. • To import a module, use the
 * globally available require function.
 *
 * Node.js 之基于文件的模块系统
 * Node.js 符合CommonJS模块规范。下面是模块系统中几个比较显著的特点:
 * 1.每个js文件是一个模块。
 * 2.每个文件通过变量module来定义模块。
 * 3.通过变量module.exports,我们可以让当前模块导出。
 * 4.通过全局函数require,导入其它模块。
 */
 

/**
 * Conditionally Load a Module
 *
 * require behaves just like any other function in JavaScript. It has no special
 * properties. This means that you can choose to call it based on some condition
 * and therefore load the module only if you need it.
 *
 * 条件性导入模块。--- require与js其它函数一样,没有特殊属性。这意味着你可以条件性的调用它,根据你的需要导入其它模块。
 *
 *
 * The require function blocks further code execution until the module has been
 * loaded. This means that the code following the require call is not executed
 * until the module has been loaded and executed. This allows you to avoid
 * providing an unnecessary callback like you need to do for all async I/O in
 * Node.js, which was discussed in Chapter 2.
 *
 * 其它:Object Factories、Shared State、Cached
 *
 * module.exports 导出的对象可以是函数,也可以是对象。如果是导出的是函数,且函数返回对象,我们就可以实现Object Factories。
 * 如果导出的对象是js对象,那么这个模块不管多少模块被导入,都是共享的--Shared State(模块被缓存了),这个共享机制可以用于配置文件中。
 * (详细代码见第三章相关)。
 *
 */
 


代码示例:

新建文件(模块)foo.js

module.exports = function(){
    console.log('a function in file foo');
}

然后,我们导入这个模块:

var foo = require('./foo');
foo();

执行结果:

a function in file foo


条件性导入模块:

var isReallyNeddFooModule = true;
if (isReallyNeddFooModule) {
    var f = require('./foo');
    f();
}


Reference:Beginning Node.js  (书)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dreamer who

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值