Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 133 ยท Getting Started

Globals and the console

Tour of Node.js globals - globalThis, process, Buffer, structuredClone, fetch, URL, AbortController, navigator, import.meta - and every console method.

Some names work in every Node file without an import: console, process, setTimeout, fetch, URL and more. These are globals, properties of one special object called globalThis. Knowing the full list tells you what is free to use, what comes from the browser world, and what is Node's own.

This lesson walks through the globals you will use every day, then goes deep on console, the tool you will reach for more than any other when you inspect values and debug.

globalThis

globalThis is the global object in every JavaScript environment. In browsers it is also called window; in Node there is no window, so globalThis is the portable name. Variables you declare with const, let or var inside a module are not put on it; only things the runtime defines (and things you assign on purpose) are.

Node.js What lives on globalThis

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Putting your own values on globalThis works, but it is a bad habit: any file can change them and nothing documents where they come from. Use modules and import instead.

process

process is Node's description of the running program, and one of the globals you will use most. A few members to know now (The process object covers it fully):

  • process.argv, process.env, process.exitCode: arguments, environment, exit status (Running Node).
  • process.platform ('linux', 'darwin', 'win32') and process.arch.
  • process.cwd(): the current working directory.
  • process.stdout and process.stderr: the streams behind console.log and console.error.
  • process.on('exit' | 'SIGINT' | ...): react to the end of the program or to signals.
  • process.memoryUsage(), process.uptime(), process.hrtime.bigint(): measurements (the values change on every run, so we never print them).
Node.js Writing straight to stdout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Buffer, TextEncoder and TextDecoder

Computers store text as bytes. Buffer is Node's classic class for raw bytes; TextEncoder and TextDecoder are the standard web versions. Buffers and text encoding have their own lessons; here is a taste.

Node.js Strings as bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The "รฉ" takes two bytes in UTF-8, so five characters become six bytes. That difference between characters and bytes matters whenever you measure sizes or slice data.

structuredClone

structuredClone(value) makes a deep copy of an object, including nested objects, arrays, Map, Set, Date and even circular references. It is the standard replacement for the old JSON.parse(JSON.stringify(x)) trick, which loses dates, Maps and undefined. It cannot copy functions or class methods.

Node.js Deep copies with structuredClone

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

URL, URLSearchParams and fetch

URL parses and builds web addresses safely, so you never concatenate query strings by hand. fetch makes HTTP requests (Node 18+; stable since 21). There is no outside network in our editor, so we call a server running on the same machine.

Node.js URL parsing and fetch to localhost

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Fetching a real site such as https://example.com would fail here with a connection error, but works on your own machine. Other web-standard globals you may meet: Request, Response, Headers, FormData, Blob, ReadableStream, WebSocket (client), URLPattern, crypto (Web Crypto) and performance.

Timers and microtasks

setTimeout, setInterval and setImmediate return objects in Node (in browsers, plain numbers). Call clearTimeout and friends to cancel them. queueMicrotask(fn) schedules a function to run right after the current code, before any timer, in the same queue promises use. Details: timers.

Node.js Timers and queueMicrotask

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

AbortController and AbortSignal

An AbortController lets one part of the program cancel work started by another. You pass its signal to an API (fetch, timers, streams, fs), and calling controller.abort() makes that work stop and reject. AbortSignal.timeout(ms) gives a signal that aborts by itself. Full coverage in abort signals.

Node.js Cancelling a timer with a signal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node 21 added a small navigator global (with hardwareConcurrency, language, platform and userAgent) so that code written for browsers can inspect its environment. The user agent starts with Node.js/ followed by the major version.

NODE
console.log(navigator.userAgent.startsWith('Node.js/'));

Some names that look global are actually provided per file:

  • In ES modules: import.meta.url (the file's file:// URL), import.meta.filename and import.meta.dirname (plain paths, available since Node 20.11).
  • In CommonJS: __filename, __dirname, require, module and exports. These do not exist in ES modules.
Node.js import.meta in an ES module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The console, method by method

console writes to two streams. console.log, info and debug go to stdout; console.error and warn go to stderr. Shells let you split them (node app.mjs > out.txt keeps errors on screen), so send diagnostics to stderr and real output to stdout.

log, formatting and placeholders

console.log accepts any number of values and prints them separated by spaces. If the first argument is a string with format codes, the rest fill them in: %s string, %d number, %i integer, %f float, %j JSON, %o and %O objects, %% a literal percent sign.

Node.js log, info, warn and placeholders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The output panel shows stdout and stderr separately. Note that console.log prints nested objects only a few levels deep (it shows [Object] beyond depth 2); console.dir fixes that.

dir

console.dir(value, options) prints an object with explicit options: depth (use null for unlimited), colors, showHidden.

Node.js console.dir with depth

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

table

console.table(data, columns?) prints arrays and objects as a table, which is excellent for lists of records.

Node.js console.table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

group, count, assert

console.group() indents everything printed until console.groupEnd(), which helps trace nested work. console.count(label) counts how often a line was reached. console.assert(condition, ...message) prints "Assertion failed" to stderr only when the condition is false and does not throw.

Node.js group, count and assert

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

time, timeLog, timeEnd and trace

console.time(label) starts a stopwatch; console.timeLog(label) prints the elapsed time without stopping it; console.timeEnd(label) prints and stops it. console.trace() prints a stack trace to stderr, showing how the code got to that line. The times differ on every run, so this is a read-only illustration of what you would see:

NODE
console.time('load');
await loadData();
console.timeLog('load', 'after loading');   // load: 12.481ms after loading
await processData();
console.timeEnd('load');                    // load: 31.904ms

Use console.time for quick checks; for serious measurement use performance.now() and node:perf_hooks (performance hooks).

Node.js console.trace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Your own console

console is an instance of the Console class, and you can create another one that writes to any streams, for example to a file or to capture output in tests.

Node.js A custom Console

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The constructor takes more options than the two streams: ignoreErrors (default true) swallows errors thrown while writing, colorMode (true, false or 'auto') decides whether util.inspect colours values, inspectOptions is passed to util.inspect (for example { depth: 0 }), and groupIndentation sets the indent used by console.group.

Node.js Console options and ANSI colours

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

That last part is how terminal colours work: an ANSI escape sequence is the byte ESC (\x1b), then [, a code and m. Codes 30 to 37 set the text colour (31 red, 32 green, 33 yellow, 34 blue, 35 magenta, 36 cyan, 37 white), 40 to 47 set the background, 1 is bold, and 0 resets everything, so always end coloured text with \x1b[0m. Only emit colours when output goes to a terminal (process.stdout.isTTY) and the user has not set NO_COLOR, otherwise log files fill up with escape codes. Node also has util.styleText('red', 'text'), which does this for you. The console additionally has console.profile(label) and console.profileEnd(label), which start and stop the inspector's CPU profiler, and console.timeStamp(label), which adds a marker to a recorded timeline; they do nothing unless a debugger or DevTools session is attached, so you will mostly meet them in browser-based debugging.

Use console.log while learning, but for real services switch to a logging library with levels and structured output. See logging.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about globalThis in Node is true?

    globalThis is the portable name for the global object. Node has no window, and module variables stay private to the module.
  2. 2. Which console method writes to stderr?

    error and warn (and trace, and a failed assert) use stderr; log, info, debug and table use stdout.
  3. 3. What happens when console.assert(false, 'oops') runs?

    console.assert only prints a message when the condition is false. It never throws; use node:assert for that.
  4. 4. Why use structuredClone(obj) rather than JSON.parse(JSON.stringify(obj))?

    The JSON trick turns dates into strings, drops undefined and Maps, and fails on cycles. structuredClone preserves them but cannot copy functions.
  5. 5. In an ES module, how do you get the path of the current file?

    __filename and __dirname exist only in CommonJS. ES modules use import.meta.url, or import.meta.filename and import.meta.dirname.

Summary

  • Globals live on globalThis; Node has process, Buffer and setImmediate, plus web APIs such as fetch, URL, AbortController, structuredClone and TextEncoder.
  • There is no window or document; navigator exists in a small form.
  • import.meta.url, import.meta.filename and import.meta.dirname replace __filename and __dirname in ES modules.
  • console.log, info and debug use stdout; error, warn and trace use stderr.
  • console.table, dir, group, count, assert and time cover most debugging; new Console(...) redirects output.

Next: Node.js vs the Browser