Comprehensive Guide to Trace Events and TTY in Node.js

Node.js provides two powerful low‑level modules for diagnostics and terminal interaction: node:trace_events — a high‑resolution tracing system that captures internal activity from V8, Node.js core, and userland code. It is essential for profiling, performance analysis, and deep debugging. node:tty — a module that exposes TTY (terminal) interfaces, enabling advanced CLI tools, raw input handling, cursor control, color detection, and terminal resizing. This guide explains both modules in a clean, structured, and practical way.

TTYTrace Events

~3 دقیقه مطالعه · آخرین به‌روزرسانی ۹ دی ۱۴۰۴

1. Introduction


The node:trace_events module provides a centralized mechanism for collecting trace data from V8, Node.js internals, and user code. The output is compatible with Chrome’s chrome://tracing tool.


2. Enabling Trace Events


2.1 Via Command Line


node --trace-event-categories v8,node,node.async_hooks app.js

2.2 Via the Module


const { createTracing } = require('node:trace_events');
const tracing = createTracing({ categories: ['node.perf'] });
tracing.enable();
// ...
tracing.disable();

3. Available Trace Categories


Node.js exposes many categories, including:

  • node.async_hooks
  • node.fs.sync / node.fs.async
  • node.net.native
  • node.perf
  • node.http
  • node.vm.script
  • v8 (GC, compilation, execution)
  • node.module_timer

4. Trace Output Files


Default filename:

node_trace.${rotation}.log

Custom pattern:

--trace-event-file-pattern '${pid}-${rotation}.log'

5. Viewing Trace Data


Open the generated log file in:

chrome://tracing

6. Core API


6.1 createTracing()


Creates a Tracing object for specific categories.

6.2 tracing.enable()


Activates tracing for the selected categories.

6.3 tracing.disable()


Deactivates tracing unless another Tracing object or CLI flag keeps it active.

6.4 getEnabledCategories()


Returns a comma‑separated list of all active categories.

7. Limitations


  • Not available inside Worker Threads.
  • Timestamps use microseconds (unlike process.hrtime() which uses nanoseconds).

8. Example: Collecting Trace Data via Inspector


Trace data can also be collected using the node:inspector module.

1. Introduction


The node:tty module provides classes for interacting with text terminals. When Node.js detects a TTY environment:

  • process.stdintty.ReadStream
  • process.stdouttty.WriteStream
  • process.stderrtty.WriteStream

2. Detecting TTY Mode


process.stdout.isTTY  // true or false

3. tty.ReadStream


  • isRaw: Indicates whether raw mode is active.
  • setRawMode(true/false): Enables or disables raw mode.

What is Raw Mode?


In raw mode:

  • Input is delivered character‑by‑character.
  • No line buffering or echoing.
  • Ctrl+C does not emit SIGINT.

4. tty.WriteStream


  • columns / rows: Terminal size.
  • cursorTo(x, y): Move cursor to absolute position.
  • moveCursor(dx, dy): Move cursor relative to current position.
  • clearLine(): Clear current line.
  • clearScreenDown(): Clear screen from cursor downward.
  • getColorDepth(): Detect color support (2, 16, 256, 16M).
  • hasColors(): Check if terminal supports a given number of colors.

5. resize Event


process.stdout.on('resize', () => {
  console.log(process.stdout.columns, process.stdout.rows);
});

6. tty.isatty()


Returns true if a file descriptor refers to a TTY.


7. Common Use Cases


  • Building advanced CLI tools
  • Interactive terminal applications
  • Custom prompts and dashboards
  • Colorful output and cursor manipulation

Conclusion


The node:trace_events and node:tty modules provide deep visibility and powerful terminal control in Node.js. Trace Events enable high‑resolution performance analysis, while TTY offers the tools needed to build sophisticated command‑line interfaces. Together, they form an essential toolkit for advanced Node.js development.


نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Comprehensive Guide to the Node.js VM Module (node:vm)

The node:vm module allows you to compile and execute JavaScript code inside isolated V8 contexts — essentially creating lightweight sandboxes within your Node.js application. These contexts have their own global scope and can run code independently from the main environment. However, vm is NOT a security sandbox. It is powerful for dynamic code execution, template engines, REPLs, plugin systems, and controlled module execution, but it must never be used to run untrusted code.

ادامه

Comprehensive Guide to the V8 Module in Node.js (node:v8)

The node:v8 module exposes low-level APIs that interact directly with the V8 JavaScript engine embedded in Node.js. . These APIs provide access to heap statistics, heap snapshots, coverage tools, serialization mechanisms, V8 flags, object queries, and promise lifecycle hooks. The module is essential for performance analysis, memory debugging, tooling, and advanced Node.js internals work.

ادامه

Comprehensive Guide to Node.js Worker Threads (node:worker_threads)

The node:worker_threads module enables true multithreading in Node.js by running JavaScript in separate threads. While Node.js is traditionally single‑threaded, worker threads allow CPU‑intensive tasks to run in parallel without blocking the event loop. They support shared memory, zero‑copy transfers, worker pools, resource limits, and advanced synchronization APIs. Worker threads are ideal for heavy computation, data processing, and parallel workloads—while async I/O remains best handled by the main thread.

ادامه

Comprehensive Guide to the Node.js util Module (node:util)

The node:util module provides a powerful collection of helper functions used throughout Node.js core and extremely useful for application developers. These utilities support debugging, inspection, formatting, type checking, callback/Promise conversions, argument parsing, text encoding, MIME handling, and more. It is one of the most versatile and essential toolkits in the Node.js ecosystem.

ادامه

Comprehensive Guide to the URL Module in Node.js

The node:url module provides tools for parsing, constructing, and manipulating URLs. Node.js supports two URL APIs: WHATWG URL API — modern, browser‑compatible, standards‑based. Legacy Node.js URL API — older, Node‑specific, now discouraged. The WHATWG API is the recommended approach for all modern applications. It provides a clean, consistent interface for working with URL components, query parameters, and structured URL patterns.

ادامه

راهنمای جامع UDP / Datagram Sockets در Node.js

ماژول node:dgram پیاده‌سازی کامل سوکت‌های UDP را در Node.js فراهم می‌کند. UDP یک پروتکل سبک، بدون اتصال (connectionless) و مناسب برای برنامه‌های بلادرنگ مانند VoIP، بازی‌ها، IoT، سیستم‌های پخش (broadcast) و چندپخشی (multicast) است. این ماژول امکان ساخت سوکت، ارسال و دریافت دیتاگرام، مدیریت TTL، عضویت در گروه‌های multicast، کنترل بافرها، و مدیریت رفتار سطح پایین شبکه را فراهم می‌کند.

ادامه