CommonJS规范

1、概述

CommonJS是服务器端模块的规范,Node.js采用了这个规范。

根据CommonJS规范,一个单独的文件就是一个模块。加载模块使用require方法,该方法读取一个文件并执行,最后返回文件内部的exports对象。下面就是一个简单的模块文件example.js。

console.log("evaluating example.js");

var invisible = function () {
  console.log("invisible");
}

exports.message = "hi";

exports.say = function () {
  console.log(message);
}

使用require方法,加载example.js

var example = require('./example.js');

这时,变量example就对应模块中的exports对象,于是就可以通过这个变量,使用模块提供的各个方法。

{
  message: "hi",
  say: [Function]
}

require方法默认读取js文件,所以可以省略js后缀名。

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

 

posted @ 2014-07-03 21:43  简简-单单  阅读(170)  评论(0编辑  收藏  举报