博客
关于我
Node第一天
阅读量:800 次
发布时间:2023-02-16

本文共 2250 字,大约阅读时间需要 7 分钟。

Node.js模块化规范与全局对象解析

CommonJS模块化规范

在Node.js中,模块化开发是核心特性之一。CommonJS是Node.js模块系统的模块化规范,遵循以下规则:

模块引入

模块间的引入使用require()方法:

const module = require('module-path');

模块暴露

模块的暴露方式有两种:

  • exports暴露:将模块输出结果直接挂载到exports对象上。
  • module.exports暴露:将模块输出结果挂载到module.exports对象上。最终,module.exports会将exports指向的值进行暴露。
  • 模块特点

    每个模块都被一个函数包裹,内部通过exportsmodule.exports暴露接口。模块加载时会执行内部函数。


    全局对象与Node.js环境

    Node.js全局对象

    Node.js提供了一个全局对象global,包含以下属性:

    • console:日志输出工具。
    • setTimeout:设置定时器。
    • setInterval:周期性执行函数。
    • setImmediate:立即执行函数。
    • Buffer:二进制数据缓冲工具。
    • process:Node.js进程管理工具。

    Node.js全局环境

    Node.js的全局环境与浏览器不同:

    • DOM:无。
    • BOM:大部分情况下无。
    • ES:支持ES6+标准。
    • global对象:核心全局变量。

    Node.js事件轮询机制

    事件轮询阶段

    Node.js事件轮询机制分为以下阶段:

  • timers(定时器阶段):执行定时器回调。
  • pending callbacks(待处理回调):处理延迟任务。
  • idle/prepare(空闲阶段):执行I/O完成回调。
  • poll(轮询阶段):轮询回调队列。
  • check(检查阶段):执行setImmediate回调。
  • close callbacks(关闭阶段):执行关闭回调。
  • 事件轮询特点

    • 循环过程:事件轮询不断重复执行各个阶段。
    • 停留阶段:大多数回调在poll阶段执行。
    • 优先级setImmediatecheck阶段优先执行。

    process.nextTick

    process.nextTick可以在任何阶段立即执行回调,适用于高优先级任务。


    包管理与依赖管理

    package.json文件

    package.json是Node.js项目的依赖管理文件,包含以下内容:

  • name:包名。
  • version:版本号。
  • dependencies:生产依赖。
  • devDependencies:开发依赖。
  • scripts:项目脚本。
  • npm命令

    • 安装依赖npm install/npm i xxx
    • 全局安装npm i -g
    • 初始化包描述文件npm init -y
    • 删除依赖npm remove xxx

    配置镜像地址

    为了加快依赖下载速度,可以配置镜像地址:

    npm config set registry http://registry.npm.taobao.org/

    yarn命令

    • 安装依赖yarn add xxx
    • 全局安装yarn global add xxx
    • 生成锁文件yarn install

    常用Node.js核心模块

    Buffer模块

    Buffer是Node.js中处理二进制数据的核心模块,主要方法包括:

    • Buffer.alloc():安全创建Buffer。
    • Buffer.from():创建Buffer。
    • Buffer.allocUnsafe():不安全创建Buffer。

    path模块

    处理文件路径的核心模块:

    const path = require('path');console.log(path.join(__dirname, '../', '文件名')); // 绝对路径

    events模块

    实现自定义事件的核心模块:

    const Emitter = require('events');const myEmitter = new Emitter();myEmitter.on('事件名', function(...args) {  console.log('事件触发');});myEmitter.emit('事件名', 1, 2, 3);

    fs模块

    文件系统核心模块,主要方法包括:

  • 同步写入文件
  • const fs = require('fs');fs.writeSync('/路径', '内容', { flags: 'w', mode: 0o666 });
    1. 异步写入文件
    2. fs.open('/路径', 'w', function(err, fd) {  fs.write(fd, '内容', function(err) {    fs.close(fd, function(err) {      // 关闭文件    });  });});
      1. 流式操作
      2. const fs = require('fs');const ws = fs.createWriteStream('/路径');ws.write('内容');

        总结

        Node.js作为前端开发框架,提供了强大的模块化能力和生态系统。通过理解CommonJS模块化规范、全局对象特性及事件轮询机制,我们可以更高效地开发Node.js应用。同时,合理使用包管理工具(如npm和yarn),优化依赖管理流程,是提升开发效率的重要手段。

    转载地址:http://kojfk.baihongyu.com/

    你可能感兴趣的文章
    npm如何清空缓存并重新打包?
    查看>>
    npm学习(十一)之package-lock.json
    查看>>
    npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
    查看>>
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>
    npm设置源地址,npm官方地址
    查看>>
    npm配置安装最新淘宝镜像,旧镜像会errror
    查看>>
    NPM酷库052:sax,按流解析XML
    查看>>
    npm错误 gyp错误 vs版本不对 msvs_version不兼容
    查看>>