nodejs学习2-模块

来源:互联网 发布:java groupingby 编辑:程序博客网 时间:2024/04/28 09:51

Node.js模块

每一个Node.js都是一个Node.js模块,包括JavaScript文件(.js)、JSON文本文件(.json)和二进制模块文件(.node)。

模块的使用

  • 方法一
    在模块文件mymodule.js中
    声明一个对象或者函数,function(){}
    然后利用node中的module.exports内置对象注册这个对象
function Hello() {    this.hello = function() {        console.log('Hello');    };    this.world = function() {        console.log('World');    };}module.exports = Hello;

在需要调用的index.js

var Hello = require('./mymodule');  //require从module.exports中找到以文件名mymodule.js命名的注册了的对象var hello = new Hello();    //再new一下这个对象就可以使用了var Hello = require('./mymodule');var hello = new Hello();hello.hello(); // >> Hellohello.world(); // >> World
  • 方法二
    注册函数
    mymodule.js里
function hello() {    console.log('Hello');}function world() {    console.log('World');}exports.hello = hello;      exports.world = world;

index.js里

var hello = require('./mymodule'); // 也可以写作 var hello = require('./mymodule.js');// 现在就可以使用mymodule.js中的函数了hello.hello(); // >> Hellohello.world(); // >> World
  • module.exports和exports
    module是一个对象,每个模块中都有一个module对象,module是当前模块的一个引用。module.exports对象是Module系统创建的,而exports可以看作是对module.exports对象的一个引用。在模块中require另一个模块时,以module.exports的值为准,因为有的情况下,module.exports和exports它们的值是不同的。module.exports和exports的关系可以表示成这样
// module.exportsexports相同的情况var m = {};        // 表示 modulevar e = m.e = {};  // e 表示 exports, m.e 表示 module.exports//===================这是在require()之前已经声明好了的=======================m.e.a = 5;  //这里相当于在mymodule.js中 module.exports.hello = hello;e.b = 6;    //这里相当于exports.hello = helloconsole.log(m.e);  // Object { a: 5, b: 6 }console.log(e);    // Object { a: 5, b: 6 }// module.exportsexports不同的情况var m = {};        // 表示 modulevar e = m.e = {};  // e 表示 exports, m.e 表示 module.exportsm.e = { c: 9 };    // m.e(module.exports)引用的对象被改了e.d = 10;console.log(m.e);  // Object { c: 9 }console.log(e);    // Object { d: 10 }
  • nodejs包
    包用于管理多个模块及其依赖关系,可以对多个模块进行封装,包的根目录必须包含package.json文件,package.json文件是CommonJS规范用于描述包的文件,符合CommonJS规范的package.json文件应该包含以下字段:
    name:包名。包名是唯一的,只能包含小写字母、数字和下划线。
    version:包版本号。
    description:包说明。
    keywords:关键字数组。用于搜索。
    homepage:项目主页。
    bugs:提交bug的地址。
    license:许可证。
    maintainers:维护者数组。
    contributors:贡献者数组。
    repositories:项目仓库托管地址数组。
    dependencies:包依赖。
$ sudo npm search express  //搜索包$ sudo npm install -g express    //安装包$ sudo npm update express  //更新包$ sudo npm uninstall express   //卸载包
0 0