|
22 | 22 | 'use strict'; |
23 | 23 |
|
24 | 24 | const util = require('util'); |
| 25 | +const kCounts = Symbol('counts'); |
25 | 26 |
|
26 | 27 | function Console(stdout, stderr, ignoreErrors = true) { |
27 | 28 | if (!(this instanceof Console)) { |
@@ -54,6 +55,8 @@ function Console(stdout, stderr, ignoreErrors = true) { |
54 | 55 | prop.value = createWriteErrorHandler(stderr); |
55 | 56 | Object.defineProperty(this, '_stderrErrorHandler', prop); |
56 | 57 |
|
| 58 | + this[kCounts] = new Map(); |
| 59 | + |
57 | 60 | // bind the prototype functions to this Console instance |
58 | 61 | var keys = Object.keys(Console.prototype); |
59 | 62 | for (var v = 0; v < keys.length; v++) { |
@@ -165,6 +168,42 @@ Console.prototype.assert = function assert(expression, ...args) { |
165 | 168 | } |
166 | 169 | }; |
167 | 170 |
|
| 171 | +// Defined by: https://console.spec.whatwg.org/#clear |
| 172 | +Console.prototype.clear = function clear() { |
| 173 | + // It only makes sense to clear if _stdout is a TTY. |
| 174 | + // Otherwise, do nothing. |
| 175 | + if (this._stdout.isTTY) { |
| 176 | + // The require is here intentionally to avoid readline being |
| 177 | + // required too early when console is first loaded. |
| 178 | + const { cursorTo, clearScreenDown } = require('readline'); |
| 179 | + cursorTo(this._stdout, 0, 0); |
| 180 | + clearScreenDown(this._stdout); |
| 181 | + } |
| 182 | +}; |
| 183 | + |
| 184 | +// Defined by: https://console.spec.whatwg.org/#count |
| 185 | +Console.prototype.count = function count(label = 'default') { |
| 186 | + // Ensures that label is a string, and only things that can be |
| 187 | + // coerced to strings. e.g. Symbol is not allowed |
| 188 | + label = `${label}`; |
| 189 | + const counts = this[kCounts]; |
| 190 | + let count = counts.get(label); |
| 191 | + if (count === undefined) |
| 192 | + count = 1; |
| 193 | + else |
| 194 | + count++; |
| 195 | + counts.set(label, count); |
| 196 | + this.log(`${label}: ${count}`); |
| 197 | +}; |
| 198 | + |
| 199 | +// Not yet defined by the https://console.spec.whatwg.org, but |
| 200 | +// proposed to be added and currently implemented by Edge. Having |
| 201 | +// the ability to reset counters is important to help prevent |
| 202 | +// the counter from being a memory leak. |
| 203 | +Console.prototype.countReset = function countReset(label = 'default') { |
| 204 | + const counts = this[kCounts]; |
| 205 | + counts.delete(`${label}`); |
| 206 | +}; |
168 | 207 |
|
169 | 208 | module.exports = new Console(process.stdout, process.stderr); |
170 | 209 | module.exports.Console = Console; |
|
0 commit comments