Node.js - 模块系统

作者: 廖马儿 | 来源:发表于2018-02-24 20:16 被阅读19次

Node.js模块系统

Node.js 有一个简单的模块加载系统。

为了让Node.js的文件可以相互调用,Node.js提供了一个简单的模块系统。
模块是Node.js 应用程序的基本组成部分,文件和模块是一一对应的。换言之,一个 Node.js 文件就是一个模块,这个文件可能是JavaScript 代码、JSON 或者编译过的C/C++ 扩展。(也就是类似于Python的py模块)

在 Node.js 中,创建一个模块非常简单,如下我们创建一个 main.js 文件,代码如下:

var hello = require('./hello');
hello.world();

以上实例中,代码 require('./hello') 引入了当前目录下的 hello.js 文件(./ 为当前目录,node.js 默认后缀为 js)。
Node.js 提供了 exports 和 require 两个对象,其中 exports 是模块公开的接口,require 用于从外部获取一个模块的接口,即所获取模块的 exports 对象。

接下来我们就来创建 hello.js 文件,代码如下:

exports.world = function() {
  console.log('Hello World');
}

下面是一样的:

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

模块的两种导出方式

1.exports.xxx = yyy
eg:
circle.js文件:

const { PI } = Math;

exports.area = (r) => PI * r ** 2;

exports.circumference = (r) => 2 * PI * r;

使用:

const circle = require('./circle.js');
console.log(`半径为 4 的圆的面积是 ${circle.area(4)}`);

circle.js 模块导出了 area() 和 circumference() 两个函数。 通过在特殊的 exports 对象上指定额外的属性,函数和对象可以被添加到模块的根部。

2.module.exports 方式
module.exports属性可以被赋予一个新的值(例如函数或对象)。

eg:
square.js文件中:

// 赋值给 `exports` 不会修改模块,必须使用 `module.exports`
module.exports = (width) => {
  return {
    area: () => width ** 2
  };
};

bar.js 用到 square 模块,上面square 导出的是一个构造函数:

const square = require('./square.js');
const mySquare = square(2);
console.log(`正方形的面积是 ${mySquare.area()}`);

一般情况下,都是模块都是导出一个对象构造器。
eg:

//hello.js 
function Hello() { 
    var name; 
    this.setName = function(thyName) { 
        name = thyName; 
    }; 
    this.sayHello = function() { 
        console.log('Hello ' + name); 
    }; 
}; 
module.exports = Hello;

这样就可以直接获得这个对象了:

//main.js 
var Hello = require('./hello'); 
hello = new Hello(); 
hello.setName('BYVoid'); 
hello.sayHello(); 

模块接口的唯一变化是使用 module.exports = Hello 代替了exports.world = function(){}。 在外部引用该模块时,其接口对象就是要输出的 Hello 对象本身,而不是原先的 exports。


服务端的模块放在哪里

我们已经在代码中使用了模块了。像这样:

var http = require("http");

...

http.createServer(...);

相关文章

  • Node.js教程(02)|基础知识篇(下)

    Node.js 模块系统 模块系统,便于各个文件之间的相互调用。在node.js中,模块就是文件,文件也是模块,这...

  • Node学习(6)--模块系统

    Node.js模块系统 为了让Node.js的文件可以相互调用,Node.js提供了一个简单的模块系统。模块是No...

  • node.js(十一)

    Node.js模块系统为了让Node.js的文件可以相互调用,Node.js提供了一个简单的模块系统。模块是Nod...

  • Node.js - 模块系统

    Node.js模块系统 Node.js 有一个简单的模块加载系统。 为了让Node.js的文件可以相互调用,Nod...

  • Node.js与内置模块

    目录: 认识Node.js fs文件系统模块 path路径模块 http模块 认识Node.js 为啥JavaSc...

  • Nodejs的模块引入与回调函数

    Node.js模块系统 在 Node.js 中,引入一个模块 如: var http=require('fs');...

  • node.js - 基础之module

    1. node.js模块概述 为了让node.js的文件可以相互调用,node.js提供了一个简单的模块系统。模块...

  • 6-1 Node.js 模块

    Node.js 的模块 为了让Node.js的文件可以相互调用,Node.js提供了一个简单的模块系统。模块是No...

  • Node.js模块系统

    一、什么是模块系统 为了让Node.js的文件可以相互调用,Node.js提供了一个简单的模块系统。模块是Node...

  • Node(3)

    一、模块系统 1.什么是模块 Node.js中常用的核心模块有: http模块 fs文件系统模块 url模块 pa...

网友评论

    本文标题:Node.js - 模块系统

    本文链接:https://www.haomeiwen.com/subject/nkjcxftx.html