CommonJS规范

一、概述服务器

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

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

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

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

exports.message = "hi";

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

使用require方法,加载example.jsspa

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

这时,变量example就对应模块中的exports对象,因而就能够经过这个变量,使用模块提供的各个方法。code

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

require方法默认读取js文件,因此能够省略js后缀名。对象

var example = require('./example');
相关文章
相关标签/搜索