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

来源:互联网 发布:推荐算法有哪些 编辑:程序博客网 时间:2024/05/02 01:36

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  (书)

0 0