@naturalcycles/nodejs-lib
Version:
Standard library for Node.js
49 lines (48 loc) • 1.64 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.inspectAny = exports.inspectAnyStringifyFn = void 0;
const util_1 = require("util");
const js_lib_1 = require("@naturalcycles/js-lib");
const INSPECT_OPT = {
breakLength: 80,
depth: 10, // default: 2
};
/**
* Just a convenience export of a const that fulfills the JsonStringifyFunction interface.
*/
const inspectAnyStringifyFn = obj => inspectAny(obj);
exports.inspectAnyStringifyFn = inspectAnyStringifyFn;
/**
* Transforms ANY to human-readable string (via util.inspect mainly).
* Safe (no error throwing).
*
* Correclty prints Errors, AppErrors, ErrorObjects: error.message + \n + inspect(error.data)
*
* Enforces max length (default to 10_000, pass 0 to skip it).
*
* Logs numbers as-is, e.g: `6`.
* Logs strings as-is (without single quotes around, unlike default util.inspect behavior).
* Otherwise - just uses util.inspect() with reasonable defaults.
*
* Returns 'empty_string' if empty string is passed.
* Returns 'undefined' if undefined is passed (default util.inspect behavior).
*
* Based on `_stringifyAny` from `js-lib`, just replaced `JSON.stringify` with `util.inspect`.
*/
function inspectAny(obj, opt = {}) {
// Inspect handles functions better
if (typeof obj === 'function') {
return (0, util_1.inspect)(obj, {
...INSPECT_OPT,
...opt,
});
}
return (0, js_lib_1._stringifyAny)(obj, {
...opt,
stringifyFn: obj => (0, util_1.inspect)(obj, {
...INSPECT_OPT,
...opt,
}),
});
}
exports.inspectAny = inspectAny;