nodeJS

来源:互联网 发布:前端防止重复提交知乎 编辑:程序博客网 时间:2024/04/30 07:45

Module node 中的模块

说明

Node.js 采用模块化结构,按照 CommonJS 规范定义和使用模块,模块与文件是一一对应的关系,即加载一个模块实际上就是加载对应的一个模块文件,每个模块都有自己的作用域,在一个文件里定义的变量、函数、类都是私有的,如果想在多个文件间分享变量,可以将其定义为 global 对象的属性 global.test = function () {}

参考

  • Node.js 文档
  • JavaScript 标准参考教程 Node.js

API

  1. require('moduleName') 用于加载指定模块
  2. module.exports = ...对外输出一个模块
  3. CommonJS 规范规定,每个模块内部,module 变量代表当前模块,这个变量是一个对象,它的 exports 属性是对外的接口,加载模块时,其实加载的是模块的 module.exports 属性
  4. exports 是Node.js 为每个模块提供的、指向 module.exports的对象,对外输出模块接口时,可以直接向 exports 对象添加方法 exports.add = function () {},但是不能直接赋值而改变指针指向 exports = function () {}
  5. CommonJS 规定,会按照代码出现顺序加载模块,模块可以多次加载,但只会在第一次加载时运行一次,然后运行结果被缓存,之后再加载就直接加载缓存结果,要想模块再次运行,必须清楚缓存
  6. 所有的缓存模块保存在 require.cache 之中,使用 delete require.cache[moduleName] 删除缓存
    // 导入模块    const test = require('./test');    // 删除指定模块的缓存    delete require.cache[__dirname + '/test.js'];    // __dirname 当前文件所在目录    console.log(__dirname); // /Users/temp/node-test    // __filename 当前文件名    console.log(__filename); // /Users/temp/node-test/index.js    // exports 是一个指向 module.exports 的变量    exports.close = function () {        console.log('close');    }    // 输出当前模块    module.exports.add = function () {        console.log('add');    }

Node.js 核心功能模块(不需要安装即可使用,但是需要require)

  • http: 提供 HTTP 服务器功能
  • url:解析URL
  • fs:与文件系统交互
  • querystring:解析URL的查询字符串
  • child_process:新建子进程
  • util:实用工具库
  • path:文件路径处理
  • crypto:加解密功能