Node.js自定义模块

Node.js自定义模块

require是一个方法,它的作用就是用来加载模块的

  • 在 Node中,模块有三种:
    • 具名的核心模块,例如fs、 http
    • 用户自己编写的文件模块

注意:相对路径必须加 ./
           可以省略后缀名(.js)
           相对路径中的./不能省略,否则报错,省略代表的是核心模块

//可以
require('./b.js')

//推荐:可以省略后缀名
require('./b')

案例1:在 a.js 中加载执行 b.js

  • a.js
console. log('a start')
require('./b.js')
console.log('a end')
  • b.js
console.log('b.js文件被加载执行了')
  • 执行:

案例2:a.js 中加载 b.js 、c.js

  • a.js
console. log('a start')
require('./b.js')
console.log('a end')
  • b.js
console.log( 'b start' )
require('./c.js ')
console.log( 'b end ' )
  • c.js
console.log('ccc')
  • 执行:
    在这里插入图片描述
  • require就是加载执行文件中的代码

在 Node 中,没有全局作用域,只有模块作用域

  • 外部访问不到内部
  • 内部也访问不到外部
  • 默认都是封闭的
  • 既然是模块作用域,那如何让模块与模块之间进行通信
  • 有时候,我们加载文件模块的目的不是为了简简单单的执行里面的代码,更重要是为了使用里面的某个成员

案例3:没有被导出的变量或方法会找不到对象

  • a.js
var foo = 'aaa'

console.log('a start')

function add(x, y) {
  return x + y
}

require('./b.js')
console.log('a end')
console.log(‘foo的值是:', foo)

  • b.js
console.log('b start')
console.log(add(1020))
var foo = " bbb'
require('./c.js ')console.log('b end')
  • 执行:

在这里插入图片描述

加载与导出

require 方法有两个作用:

  1. 加载文件模块并执行里面的代码
  2. 拿到被加载文件模块导出的接口对象
    在每个文件模块中都提供了一个对象:exports
    exports 默认是一个空对象
    你要做的就是把所有需要被外部访问的成员挂载到这个 exports 对象中

案例4:调用 b.js 对象中的值及方法

a.js

var bExports = require('./b')

console.log(bExports.foo)

console.log(bExports.add(10, 30))

b.js

var foo = 'bbb'

exports.foo = 'hello'

exports.add = function (x, y) {
  return x + y
}

在这里插入图片描述

案例5:调用b.js中的 age 的值

a.js

var bExports = require('./b')

console.log(bExports.age)

b.js

var age = 18

exports.age = age

结果:18

本文来自博客园,作者:兮动人,转载请注明原文链接:https://www.cnblogs.com/xdr630/p/15254830.html

原文地址:https://www.cnblogs.com/xdr630/p/15254830.html