npm 是 JavaScript 的包管理系统, 提供通用的模块给其他开发者及工程内使用, 类似于 Java 语言 的 maven 库, 设计师使用的素材库.
好用的 npm 包系列致力于挖掘一些好玩实用的 npm 包, 聊些使用场景和实现思路. 如果说程序员喜欢用自己的方式去实现别人已实现的东西, 叫做重复造轮子, 那么这个系列就是带你去看飞轮海 .
基本介绍
DEBUG 是一种计算机程序. 马克 2 号 (Harvard Mark II) 编制程序的葛丽丝. 霍波 (Grace Hopper) 是一位美国海军准将及计算机科学家, 同时也是世界最早的一批程序设计师之一. 有一天, 她在调试设备时出现故障, 拆开继电器后, 发现有只飞蛾被夹扁在触点中间, 从而 "卡" 住了机器的运行. 于是, 霍波诙谐的把程序故障统称为 "臭虫(BUG)", 把排除程序故障叫 DEBUG, 而这奇怪的 "称呼", 竟成为后来计算机领域的专业行话.
https://www.npmjs.com/package/debug 在 npm 上周下载量 1 千八百万 +,github 上有 6k + 的 star, 是一个受关注的高频基础包.
基本使用场景
主要的功能包括命名空间和色彩定义, 毫秒级时间差, printf 语法变量替换, 附带个函数性能比较的代码示例意思一下.
- // 计算函数性能示例, 传入一个纯数字数组, 计算其平均值
- // avgA 使用 lodash 库中 sum 求和
- // avgB 使用 ES5 中 Array.proptype.reduce 求和
- const _ = require('lodash');
- const debug = require('debug');
- const debugA = debug('avgA:');
- const debugB = debug('avgB:');
- const testFixture = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
- // 使用 lodash sum 求和
- function avgA(arr) {
- return _.sum(arr) / arr.length;
- }
- // 使用原生 reduce 求和
- function avgB(arr) {
- return arr.reduce((cal, curr) => cal + curr, 0) / arr.length;
- }
- const range = _.range(0, 10000000, 1);
- range.forEach((index) => {
- const result = avgA(testFixture);
- if (index % 1000000 === 0) {
- debugA('time %d', index);
- }
- })
- range.forEach((index) => {
- const result = avgB(testFixture);
- if (index % 1000000 === 0) {
- debugB('time %d', index);
- }
- })
运行结果:
使用场景 1: 项目中根据环境开启 debug
实际项目中, 往往线下环境要开启调试, 而线上环境要有条件开启.
- const _ = require('lodash');
- const debug = require('debug');
- const debugA = debug('A:');
- const debugB = debug('B:');
- // 当环境为 production 时, 所有的 debugA 均不会输出
- if (process.env.NODE_ENV === 'production') {
- debugA.enabled = false;
- }
- debugA('hello world');
- debugB('I am new to debug');
运行结果:
使用场景 2: 展示有意思的字符画
我们是一群有着特殊信仰的群体...
顺便打个广告? AIS-TXD 招人, 前端 / 设计师快到碗里来, 简历速投 txd-jobs@list.alibaba-inc.com
代码分析
源码可以看下官方 github https://github.com/visionmedia/debug/tree/master , 基本逻辑如下:
环境判断分发 Node.js 使用 /node.js , browser 使用 /browser.js
node.js 部分 处理命令行启动指令, 颜色定义和命令行展示库 tty https://nodejs.org/api/tty.html
brower.js 部分 处理 js 申明配置, 颜色定义(枚举 web 安全色值), 底层使用 console.log
common.js 部分, 通用逻辑, 包含实例创建, 启用开关, 色彩选择, printf 语法等
本期的 npm 包 debug 就介绍到这里, 遇到有相似场景的情况就放心使用吧, 还有什么实用的 npm 包欢迎在留言区推荐啦.
关注查看更多原创内容
关注公众号投递简历 (招聘视觉, 交互, 前端)
来源: https://juejin.im/post/5aeab5d46fb9a07aae1502cc