CodeBlanks Logo Icon CodeBlanks

Summary - Debugging

Combine inspect, console and util.inspect to write a debug session.

Summary - Debugging

In this group you learned Node.js's debugging tools: the node inspect terminal debugger, the Chrome DevTools visual interface, console methods, object inspection with util.inspect, and source map mapping to the original source. Now we will combine them in a debugging helper.

Structure: format objects with util.inspect, give general output with console.log, write errors separately with console.error. This is a small example of what a logging helper looks like in a real project. Choosing the right tool during debugging saves time: console.log for quick inspection, DevTools for visual inspection, node inspect for stepping line by line.

Practice Write a debugging helper

Import with const util = require("node:util");. Define const record = { name: "Ayşe", age: 30, grades: [85, 90, 78] };. Define function debugLog(title, data) { console.log(title + ": " + util.inspect(data, { depth: 2, colors: false })); }. Call with debugLog("Record", record). Add console.log("Debugging done").

Starter code

index.js
// Import util
// write here

// Define the record object
// write here

// Define the debugLog function
// write here

// Call debugLog
// write here

// Print "Debugging done"
// write here

Sample solution

index.js
const util = require("node:util");
const record = { name: "Ayşe", age: 30, grades: [85, 90, 78] };
function debugLog(title, data) {
  console.log(title + ": " + util.inspect(data, { depth: 2, colors: false }));
}
debugLog("Record", record);
console.log("Debugging done");

Expected output

Kayıt: { ad: 'Ayşe', yas: 30, notlar: [ 85, 90, 78 ] }
Ayıklama tamam

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which tool is best for inspecting a complex object?

index.js
util.inspect(obj, { depth: 3 })
  • Only console.log
  • Only process.exit
  • Formatting with util.inspect and passing it to console.log Correct answer
  • throw new Error

Explanation: util.inspect formats the object readably.

2 Match each tool to its purpose

Term Meaning
node inspect Terminal debugger
DevTools Visual interface
console.error Error stream
util.inspect Object formatting

3 Complete the inspect call

Question
console.log(util.____(record, { depth: 2 }));
Answer
console.log(util.inspect(record, { depth: 2 }));

Explanation: util.inspect turns the record object into a string.

All lessons in Intermediate