0% found this document useful (0 votes)
35 views5 pages

Node.js Debug Module Implementation

This document is a Node.js module that implements a debugging utility with various functions such as logging, formatting arguments, and managing color output. It includes features for handling environment variables related to debugging options and provides ANSI color escape codes for enhanced output. Additionally, it has deprecated methods and manages namespaces for debugging instances.

Uploaded by

mrmarktyy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views5 pages

Node.js Debug Module Implementation

This document is a Node.js module that implements a debugging utility with various functions such as logging, formatting arguments, and managing color output. It includes features for handling environment variables related to debugging options and provides ANSI color escape codes for enhanced output. Additionally, it has deprecated methods and manages namespaces for debugging instances.

Uploaded by

mrmarktyy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

/**

* Module dependencies.
*/

const tty = require('tty');


const util = require('util');

/**
* This is the [Link] implementation of `debug()`.
*/

[Link] = init;
[Link] = log;
[Link] = formatArgs;
[Link] = save;
[Link] = load;
[Link] = useColors;
[Link] = [Link](
() => {},
'Instance method `[Link]()` is deprecated and no longer does anything.
It will be removed in the next major version of `debug`.'
);

/**
* Colors.
*/

[Link] = [6, 2, 3, 4, 5, 1];

try {
// Optional dependency (as in, doesn't need to be installed, NOT like
optionalDependencies in [Link])
// eslint-disable-next-line import/no-extraneous-dependencies
const supportsColor = require('supports-color');

if (supportsColor && ([Link] || supportsColor).level >= 2) {


[Link] = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error) {
// Swallow - we only care if `supports-color` is available; it doesn't have
to be.
}

/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node [Link]
*/

[Link] = [Link]([Link]).filter(key => {


return /^debug_/[Link](key);
}).reduce((obj, key) => {
// Camel-case
const prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/g, (_, k) => {
return [Link]();
});

// Coerce string value into JS value


let val = [Link][key];
if (/^(yes|on|true|enabled)$/[Link](val)) {
val = true;
} else if (/^(no|off|false|disabled)$/[Link](val)) {
val = false;
} else if (val === 'null') {
val = null;
} else {
val = Number(val);
}

obj[prop] = val;
return obj;
}, {});

/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/

function useColors() {
return 'colors' in [Link] ?
Boolean([Link]) :
[Link]([Link]);
}

/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/

function formatArgs(args) {
const {namespace: name, useColors} = this;

if (useColors) {
const c = [Link];
const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
const prefix = ` ${colorCode};1m${name} \u001B[0m`;
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
[Link](colorCode + 'm+' + [Link]([Link]) + '\
u001B[0m');
} else {
args[0] = getDate() + name + ' ' + args[0];
}
}

function getDate() {
if ([Link]) {
return '';
}
return new Date().toISOString() + ' ';
}

/**
* Invokes `[Link]()` with the specified arguments and writes to
stderr.
*/

function log(...args) {
return
[Link]([Link]([Link], ...args) + '\n');
}

/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (namespaces) {
[Link] = namespaces;
} else {
// If you set a [Link] field to null or undefined, it gets cast to
the
// string 'null' or 'undefined'. Just delete instead.
delete [Link];
}
}

/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/

function load() {
return [Link];
}

/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init(debug) {
[Link] = {};

const keys = [Link]([Link]);


for (let i = 0; i < [Link]; i++) {
[Link][keys[i]] = [Link][keys[i]];
}
}

[Link] = require('./common')(exports);

const {formatters} = [Link];

/**
* Map %o to `[Link]()`, all on a single line.
*/

formatters.o = function (v) {


[Link] = [Link];
return [Link](v, [Link])
.split('\n')
.map(str => [Link]())
.join(' ');
};

/**
* Map %O to `[Link]()`, allowing multiple lines if needed.
*/

formatters.O = function (v) {


[Link] = [Link];
return [Link](v, [Link]);
};

Common questions

Powered by AI

The `useColors` function checks if the `colors` property exists in the `exports.inspectOpts` object. If it exists, it returns a boolean value of `exports.inspectOpts.colors`; otherwise, it checks if `process.stderr.fd` is a TTY to enable colored output .

The debug module maps environment variables into `inspectOpts` by filtering keys starting with 'DEBUG_', transforming them into camel-case, and coercing their values into appropriate JavaScript types like booleans or numbers. This transformation allows for easy tweaking of debugging behavior via environment settings, providing developers with a seamless configuration mechanism .

Environment variables prefixed with 'DEBUG_' are filtered, and their values are transformed into JavaScript types (e.g., true, false, numbers) to form properties of the `inspectOpts` object. The keys are converted to camel-case. The values are coerced as necessary, such as converting 'true' to boolean true or '10' to the number 10, ensuring the debug module interprets them correctly .

The dependency on `supports-color` in the `debug` module enables fine-grained control over color outputs by checking terminal support levels. This dependency dictates the color palette availability and ensures compatibility across terminals supporting different color depths. When unavailable, the module defaults to a smaller color set, thus maintaining functionality while limiting the color variation. This design balances enhanced UX with flexibility in various environments .

The `save` function sets the `DEBUG` environment variable to the provided namespaces or deletes the variable if no namespaces are provided. The `load` function retrieves the value of the `DEBUG` environment variable, allowing for the persistence of the debug modes across sessions .

The `formatArgs` function formats the arguments for console output by adding ANSI color escape codes if colors are enabled. It prefixes the first argument with color codes based on the namespace and color assigned to it, which are integrated into the message before the formatted output gets logged .

The `debug` module enhances `util.inspect()` with formatters `%o` and `%O` for different output requirements: `%o` formats objects on a single line for concise display, while `%O` allows multiline outputs for detailed inspection. The module integrates these with the configured `inspectOpts` to adjust output readability according to user settings, leveraging coloring features for enhanced visibility .

The `debug` module initializes specific debug instances with localized configurations by creating a new `inspectOpts` object within each instance. This customization ensures that changes in one instance's settings won't affect others, allowing for tailored debugging outputs based on the context .

The `debug` module uses the `util.deprecate` method to handle deprecated features, with the `destroy` method as an example. It wraps the method in `util.deprecate`, signaling to developers that `debug.destroy()` is deprecated and non-functional using a warning, indicating it will be removed in the next major version. This approach effectively communicates forthcoming changes without causing immediate disruption to existing code .

ANSI escape codes in the `debug` module are used to apply colors and formatting styles to console output, enhancing readability and visual distinction. They wrap around message prefixes and suffixes, marking the start and end of the formatting, thereby visually grouping related log messages. This use of ANSI codes relies on the `useColors` function to decide when to apply these codes, based on environment settings and terminal capabilities .

You might also like