Skip to content

Commit 840a9b4

Browse files
author
DilongFa
committed
Initial release
0 parents  commit 840a9b4

5 files changed

Lines changed: 239 additions & 0 deletions

File tree

.gitignore

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Dependency directory
2+
node_modules
3+
# Optional npm cache directory
4+
.npm
5+
6+
test.js
7+
8+
# Logs
9+
logs
10+
*.log
11+
12+
# Runtime data
13+
pids
14+
*.pid
15+
*.seed
16+
17+
*.csv
18+
*.dat
19+
*.out
20+
*.gz
21+
*.swp
22+
23+
# Directory for instrumented libs generated by jscoverage/JSCover
24+
lib-cov
25+
# Coverage directory used by tools like istanbul
26+
coverage
27+
# node-waf configuration
28+
.lock-wscript
29+
# Compiled binary addons (http://nodejs.org/api/addons.html)
30+
build/Release
31+
# Optional REPL history
32+
.node_repl_history
33+
.c9
34+
# Editors
35+
.vscode
36+
.history
37+
.idea
38+
# OS metadata
39+
.DS_Store
40+
Thumbs.db
41+
.DocumentRevisions-V100
42+
.fseventsd
43+
.Spotlight-V100
44+
.TemporaryItems
45+
.Trashes
46+
.VolumeIcon.icns
47+
.com.apple.timemachine.donotpresent

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2018 DiLong Fa
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# debug
2+
A simple debugging utility for Node.js
3+
4+
### Installation
5+
```
6+
npm i @dilongfa/debug
7+
```
8+
9+
### Setup
10+
```javascript
11+
const debug = require('@dilongfa/debug')('app')
12+
debug('Hello world!')
13+
```
14+
15+
### Run
16+
```
17+
DEBUG=app node index.js
18+
```

index.js

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
'use strict'
2+
3+
const util = require('util')
4+
const allows = []
5+
const ignores = []
6+
const colors = [2, 3, 4, 5, 6]
7+
let counter = 0
8+
9+
function ms(ms) {
10+
if (ms >= 86400000) return Math.round(ms / 86400000) + 'd'
11+
if (ms >= 3600000) return Math.round(ms / 3600000) + 'h'
12+
if (ms >= 60000) return Math.round(ms / 60000) + 'm'
13+
if (ms >= 1000) return Math.round(ms / 1000) + 's'
14+
return ms + 'ms'
15+
}
16+
17+
function fillColor(str, c = 0) {
18+
return '\u001b[3' + c + ';1m' + str + '\u001b[0m'
19+
}
20+
21+
function getColor() {
22+
let c = (counter % colors.length)
23+
counter++
24+
return (c === 0) ? 2 : 2+c
25+
}
26+
27+
function formatError(e) {
28+
return e.stack.split('\n').map((str, i) => {
29+
if (i == 0) return e.message
30+
if (i == 1) return fillColor(str.replace('at', '@'), 0).replace(/\((.*)\)/, fillColor('($1)', 1))
31+
return fillColor(str.replace('at', '@'), 0)
32+
}).join('\n')
33+
}
34+
35+
const formatters = {
36+
o: (v) => util.inspect(v, {colors: true}).replace(/\s*\n\s*/g, ' '), //.split('\n').map(str => str.trim()).join(' '),
37+
O: (v) => (v instanceof Error) ? formatError(v) : util.inspect(v, {colors: true})
38+
}
39+
40+
function getState(ns) {
41+
if (process.env.DEBUG === '*') {
42+
return true
43+
}
44+
45+
for (let elm of ignores) {
46+
if (elm.test(ns)) return false
47+
}
48+
49+
for (let elm of allows) {
50+
if (elm.test(ns)) return true
51+
}
52+
53+
return false
54+
}
55+
56+
function load(ns) {
57+
if (!ns) ns = process.env.DEBUG
58+
59+
let ary = (typeof ns === 'string' ? ns : '').split(/[\s,]+/)
60+
for (let elm of ary) {
61+
if (!elm) continue
62+
ns = elm.replace(/\*/g, '.*?')
63+
if (ns[0] === '-') {
64+
ignores.push(new RegExp('^' + ns.slice(1) + '$'))
65+
} else {
66+
allows.push(new RegExp('^' + ns + '$'))
67+
}
68+
}
69+
}
70+
71+
function Debug(namespace) {
72+
this._namespace = namespace
73+
this._color = getColor()
74+
this._previous = null
75+
this._enabled = getState(namespace)
76+
return this.debug.bind(this)
77+
}
78+
79+
Debug.prototype.debug = function(...args) {
80+
if (!this._enabled || args.length === 0) return
81+
82+
const now = Date.now()
83+
const duration = now - (this._previous || now)
84+
this._previous = now
85+
86+
// Parse and reformat messages
87+
if (typeof args[0] !== 'string') {
88+
args.unshift('%O')
89+
} else if (args[1] instanceof Error && args[0].indexOf('%O') == -1) {
90+
args[0] = args[0].trim() + ' %O'
91+
}
92+
93+
let idx = 0
94+
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, flag) => {
95+
if (match === '%%') return match
96+
idx++
97+
if (typeof formatters[flag] == 'function' && args[idx]) {
98+
match = formatters[flag](args[idx])
99+
args.splice(idx, 1)
100+
idx--
101+
}
102+
return match
103+
})
104+
105+
const prefix = fillColor(this._namespace, this._color)
106+
const suffix = '\u001b[3' + this._color + 'm' + '+' + ms(duration) + '\u001b[0m'
107+
108+
args[0] = ' ' + prefix + ' ' +args[0].split('\n').join('\n ' + prefix)
109+
args.push(suffix)
110+
111+
// Output
112+
process.stdout.write(util.format(...args) + '\n');
113+
}
114+
115+
load()
116+
117+
module.exports = (namespace) => new Debug(namespace)

package.json

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
{
2+
"name": "@dilongfa/debug",
3+
"version": "1.0.0",
4+
"description": "A simple debugging utility for Node.js",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 0"
8+
},
9+
"publishConfig": {
10+
"access": "public"
11+
},
12+
"repository": {
13+
"type": "git",
14+
"url": "git+https://github.com/dilongfa/node-debug.git"
15+
},
16+
"keywords": [
17+
"console",
18+
"debug",
19+
"print",
20+
"echo",
21+
"log",
22+
"node-print",
23+
"pretty-print",
24+
"print-console",
25+
"node-debug",
26+
"nodejs-debug",
27+
"debugjs"
28+
],
29+
"author": "DiLong Fa <dilongfa@gmail.com>",
30+
"license": "MIT",
31+
"bugs": {
32+
"url": "https://github.com/dilongfa/node-debug/issues"
33+
},
34+
"homepage": "https://github.com/dilongfa/node-debug#readme",
35+
"devDependencies": {}
36+
}

0 commit comments

Comments
 (0)