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 (书)
- Node.js 之基于文件的模块系统
- Node.js之模块系统
- Node.js 的模块系统
- Node.js模块系统
- Node.js模块系统
- Node.js模块系统
- Node.js模块系统
- Node.js模块系统
- Node.js 模块系统
- Node.js模块系统
- Node.js模块系统
- node.js之模块
- Node.js之模块的基本概念
- JavaScript基础之Node.js的模块
- 基于Node.js的文件下载服务器
- 基于Node.js的文件下载服务器
- node.js基于工厂方法的mysql模块封装
- 基于Redis的简单消息队列模块(Node.js)
- LeetCode 之 Kth Largest Element in an Array — C++ 实现
- C++ 链表实现通讯录 (关于获取鼠标句柄后,清屏不能再次获取)
- 关于Java SE、Java EE、Java ME三者的认识
- 基于power supply信息传递的uevent机制
- php导出word文档样式,与需求给你的word文档一模一样。
- Node.js 之基于文件的模块系统
- Cocos Studio工程分析
- android 改变ImageView的颜色(Alpha值、Red值、Green值、Blue值)
- 原路归并排序
- 存储过程与游标
- Redis AOF持久化
- python脚本调用c/c++库,以opencv的python接口为例
- POJ 2828 Buy Tickets(线段树)
- xrdp安装配置