How do you log deeply nested objects completely in Node.js console.log instead of [Object]? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you log deeply nested objects completely in Node.js console.log instead of [Object]?

message-square
0

To log deeply nested objects completely in Node.js instead of seeing truncated [Object] or [Array] placeholders, validate your target input and util.inspect options with typeof / instanceof / Array.isArray checks, format the value using util.inspect(targetValue, { depth: null, colors: true, compact: false }) (or write to a file/stream for very large payloads) inside a try / catch block, and use a Map when tracking inspection profiles or serializing nested records without Object.prototype collisions.


1. Logging Deeply Nested Objects with util.inspect(..., { depth: null }) and try / catch

Node.js’s console.log() delegates object formatting to util.inspect(), which defaults to a limited nesting depth (depth: 2 in many Node versions); pass depth: null (and maxArrayLength: null when needed) inside try / catch so nested levels expand completely:

// Format and log deeply nested values in Node.js without [Object] truncation
function logDeepObjectInNode(targetValue, utilModule, {
  label = "DeepObject",
  depth = null,
  maxArrayLength = null,
  colors = true,
  compact = false
} = {}) {
  if (!utilModule || typeof utilModule.inspect !== "function") {
    throw new TypeError("Expected utilModule to provide a util.inspect() function (e.g., node:util).");
  }
  if (typeof label !== "string" || label.trim().length === 0) {
    throw new TypeError("Expected label to be a non-empty string.");
  }
  if (depth !== null && (typeof depth !== "number" || !Number.isInteger(depth) || depth < 0)) {
    throw new RangeError("Expected depth to be null or a non-negative integer.");
  }
  if (maxArrayLength !== null && (typeof maxArrayLength !== "number" || !Number.isInteger(maxArrayLength) || maxArrayLength < 0)) {
    throw new RangeError("Expected maxArrayLength to be null or a non-negative integer.");
  }
  if (typeof colors !== "boolean") {
    throw new TypeError("Expected colors to be a boolean.");
  }
  if (typeof compact !== "boolean") {
    throw new TypeError("Expected compact to be a boolean.");
  }

  try {
    const formattedText = utilModule.inspect(targetValue, {
      depth,
      maxArrayLength,
      colors,
      compact,
      getters: false
    });

    console.log(`--- ${label.trim()} ---\n${formattedText}`);
    return formattedText;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed inspecting/logging deep object for "${label}": ${message}`);
  }
}

// Example usage (Node.js):
// import util from "node:util";
// try {
//   const nestedPayload = {
//     service: {
//       auth: {
//         session: {
//           tokens: { access: { scopes: ["read", "write"] } }
//         }
//       }
//     }
//   };
//   logDeepObjectInNode(nestedPayload, util, { label: "AuthSession" });
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Set depth: null for unlimited nesting depth: Prints every nested object level instead of collapsing deeper layers into [Object].
  • Avoid JSON.stringify(obj, null, 2) alone when objects have circular references, BigInt, Map/Set, or undefined properties: util.inspect() handles circular references and Node/JS built-ins cleanly.

2. Converting Nested Objects and Maps Safely with a Map Registry

When inspecting multiple named objects or normalizing nested records into a Map before logging, store profiles and entries in a Map so dynamic keys never collide with Object.prototype properties:

// Inspect multiple named values using a profile Map and return a Map of formatted outputs
function inspectNamedObjectsWithMap(entriesMap, utilModule, profileName = "full", profilesMap = new Map([
  ["full", { depth: null, maxArrayLength: null, colors: false, compact: false }],
  ["shallow", { depth: 2, maxArrayLength: 20, colors: false, compact: true }]
])) {
  if (!(entriesMap instanceof Map)) {
    throw new TypeError("Expected entriesMap to be a Map instance.");
  }
  if (!utilModule || typeof utilModule.inspect !== "function") {
    throw new TypeError("Expected utilModule to provide a util.inspect() function.");
  }
  if (typeof profileName !== "string" || profileName.trim().length === 0) {
    throw new TypeError("Expected profileName to be a non-empty string.");
  }
  if (!(profilesMap instanceof Map)) {
    throw new TypeError("Expected profilesMap to be a Map instance.");
  }

  try {
    const cleanProfile = profileName.trim();
    const inspectOpts = profilesMap.get(cleanProfile);

    if (typeof inspectOpts !== "object" || inspectOpts === null || Array.isArray(inspectOpts)) {
      throw new Error(`Unknown inspection profile "${cleanProfile}".`);
    }

    const formattedMap = new Map();

    for (const [entryKey, entryVal] of entriesMap.entries()) {
      if (typeof entryKey !== "string" || entryKey.trim().length === 0) {
        throw new TypeError("Expected every key in entriesMap to be a non-empty string.");
      }
      formattedMap.set(entryKey.trim(), utilModule.inspect(entryVal, inspectOpts));
    }

    return formattedMap;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed formatting named objects Map: ${message}`);
  }
}

// Example usage (Node.js):
// import util from "node:util";
// try {
//   const targets = new Map([
//     ["requestContext", { user: { profile: { role: "admin" } } }],
//     ["configMap", new Map([["retries", 3], ["timeoutMs", 5000]])]
//   ]);
//   const outputMap = inspectNamedObjectsWithMap(targets, util, "full");
//   console.log(outputMap.get("configMap"));
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Use Map rather than {} for inspection names and dynamic keys: Avoids collisions with Object.prototype properties (constructor, toString, hasOwnProperty).
  • Disable ANSI colors (colors: false) when writing formatted strings to log files: Prevents escape sequences from polluting plain-text log files.

3. Terminal Buffer Limits, Circular References, and Production Caveats

Keep these Node.js logging details in mind when printing deep structures:

  • Huge nested dumps can flood stdout or terminal scrollback: When inspecting very large objects or deep trees in production or debugging, filter keys first or write output to a log file rather than dumping massive strings to stdout on every request.
  • Circular references are detected automatically by util.inspect(): Node prints [Circular *1] instead of throwing a TypeError: Converting circular structure to JSON.
  • Avoid leaving depth: null full-object dumps inside hot production request handlers: Keep deep inspection scoped to local debugging, error diagnostics, or structured logging pipelines.