每一个 Node.js 文件都是一个 Node.js 模块,包括JavaScript文件(.js)、JSON文本文件(.json)和二进制模块文件(.node)。
模块的使用
新建一个mymodule.js文件
第一种方法:
function hello() {
console.log('hello!');
}
export.hello = hello;
在其他模块中,载入该模块:
var hello = require('./mymodule');
hello.hello(); >>Hello!
第二种方法:
funcion Hello(){
this.hello = function() {
console.log('Hello!');
}
}
module.export = Hello;
其他模块中载入该模块:
var Hello = require('./mymodule');
var hello = new Hello();
Hello.hello; >>Hello!
Node.js包(package)
包用于管理多个模块及其依赖关系,可以对多个模块进行封装,包的根目录必须包含package.json文件,package.json文件是CommonJS规范用于描述包的文件,符合CommonJS规范的package.json文件一般包含以下字段:
name:包名。包名是唯一的,只能包含小写字母、数字和下划线。
version:包版本号。
description:包说明。
keywords:关键字数组。用于搜索。
homepage:项目主页。
bugs:提交bug的地址。
license:许可证。
maintainers:维护者数组。
contributors:贡献者数组。
repositories:项目仓库托管地址数组。
dependencies:包依赖。
下面是一个package.json示例:
{
"name": "shiyanlou",
"description": "Shiyanlou test package.",
"version": "0.1.0",
"keywords": [
"shiyanlou",
"nodejs"
],
"maintainers": [{
"name": "test",
"email": "test@shiyanlou.com"
}],
"contributors": [{
"name": "test",
"web": "http://www.shiyanlou.com/"
}],
"bugs": {
"mail": "test@shiyanlou.com",
"web": "http://www.shiyanlou.com/"
},
"licenses": [{
"type": "Apache License v2",
"url": "http://www.apache.org/licenses/apache2.html"
}],
"repositories": [{
"type": "git",
"url": "http://github.com/test/test.git"
}],
"dependencies": {
"webkit": "1.2",
"ssl": {
"gnutls": ["1.0", "2.0"],
"openssl": "0.9.8"
}
}
}
package.json文件可以自己手动编辑,但为了方便,更推荐通过npm init命令进行生成。你可以自己尝试在终端中输入npm init命令来生成一个包含package.json文件的包。
npm
由于实验楼环境网络限制,所以npm命令会连接taobao的源,而不会直接连接官方源。
npm 也可以从第三方网站(http://www.npmjs.org/)上下载第三方Node.js包。
通过npm安装的包会按包名字母顺序出现在package.json中的dependencies字段中。
$ npm search express //搜索express包
$ npm install -g express //安装包,-g即global全局安装
$ npm update express
$ npm uninstall express //卸载包