# Node.js API compatibility - Process

The `process` module in Node.js is a global object that provides information and control over the current Node.js process. It's essential for interacting with the runtime environment and managing the execution of Node.js applications. This module is available in the Azion Runtime through Node.js compatibility, where a frequent use case is reading environment variables, such as `process.env`, or scheduling work with `nextTick` inside a function.

---

## Example: Environment variables and nextTick

The example below shows how to use the `process` module in a function:

```javascript
/**
 * An example of using the Node.js Process API in an Azion Function.
 * Support:
 *  - Extended by library `process`
 *    Portions of this file Copyright Roman Shtylman, licensed under the MIT license.
 * @module runtime-apis/nodejs/process/main
 * @example
 * // Execute with Azion Bundler:
 * npx edge-functions build
 * npx edge-functions dev
 */
import { env, nextTick } from "node:process";

/**
 * Example of using the process api
 * @param {*} event
 */
const main = async (event) => {
  console.log(process.env.NODE_ENV);

  nextTick(() => {
    console.log("Hello, Next Tick!");
    // Hello, Next Tick!
  });

  return new Response(`NODE_ENV: ${process.env.NODE_ENV}`, { status: 200 });
};

export default main;
```

---

## Example: Reading configuration from environment variables

Access configuration values stored in environment variables:

```javascript
import process from "node:process";

const main = async (event) => {
  // Read environment variables
  const nodeEnv = process.env.NODE_ENV || "development";
  const apiKey = process.env.API_KEY;
  const debug = process.env.DEBUG === "true";
  const maxRetries = parseInt(process.env.MAX_RETRIES || "3", 10);

  console.log("Environment:", nodeEnv);
  console.log("Debug mode:", debug);
  console.log("Max retries:", maxRetries);

  // Check if required variables are set
  if (!apiKey) {
    console.warn("API_KEY not configured");
  }

  // Build configuration object
  // Security: Never expose sensitive env vars in responses
  // Use boolean flags instead of actual values
  const config = {
    environment: nodeEnv,
    debug,
    maxRetries,
    hasApiKey: !!apiKey  // Boolean only, not the actual key
  };

  return new Response(JSON.stringify(config), {
    headers: { "Content-Type": "application/json" }
  });
};

export default main;
```

---

## Example: Using nextTick for deferred execution

Schedule work to run after the current operation completes:

```javascript
import { nextTick } from "node:process";
import { setTimeout } from "node:timers/promises";

const main = async (event) => {
  const executionOrder = [];

  executionOrder.push("Start");

  // Schedule with nextTick - runs after current code
  // Note: nextTick execution order may differ from standard Node.js
  // in edge runtime environments
  nextTick(() => {
    executionOrder.push("NextTick callback");
    console.log("Deferred execution completed");
  });

  executionOrder.push("After nextTick call");

  // Multiple nextTick calls execute in order
  nextTick(() => {
    executionOrder.push("Second nextTick");
  });

  // Wait for nextTick callbacks to execute
  await setTimeout(10);

  executionOrder.push("End");

  console.log("Execution order:", executionOrder.join(" -> "));

  return new Response(JSON.stringify({ executionOrder }), {
    headers: { "Content-Type": "application/json" }
  });
};

export default main;
```

---

## Example: Process information and platform detection

Access runtime information about the process:

```javascript
import process from "node:process";

const main = async (event) => {
  // Note: In Azion Runtime, some process properties may return
  // fixed or environment-specific values:
  // - process.pid may always return a fixed value
  // - process.arch reflects the edge node architecture
  // - process.versions may not include all Node.js version fields

  // Platform information
  const platform = process.platform;
  const arch = process.arch;
  const versions = process.versions;

  // Process identification
  const pid = process.pid;
  const ppid = process.ppid;

  // Runtime information
  const nodeVersion = process.version;
  const v8Version = versions.v8;

  console.log("Platform:", platform);
  console.log("Architecture:", arch);
  console.log("Node version:", nodeVersion);
  console.log("V8 version:", v8Version);
  console.log("Process ID:", pid);

  // Build info object with fallbacks for potentially undefined values
  const processInfo = {
    platform,
    arch,
    pid,
    ppid,
    nodeVersion,
    v8Version,
    versions: {
      node: versions.node || "unknown",
      v8: versions.v8 || "unknown",
      openssl: versions.openssl || "unknown"
    }
  };

  return new Response(JSON.stringify(processInfo, null, 2), {
    headers: { "Content-Type": "application/json" }
  });
};

export default main;
```

---

## Example: Memory usage monitoring

Monitor memory consumption during execution:

```javascript
import process from "node:process";

const main = async (event) => {
  // Get initial memory usage
  const initialMemory = process.memoryUsage();

  // Simulate some work
  const data = [];
  for (let i = 0; i < 1000; i++) {
    data.push({ id: i, data: "x".repeat(100) });
  }

  // Get memory usage after work
  const finalMemory = process.memoryUsage();

  // Calculate memory delta
  const memoryDelta = {
    rss: finalMemory.rss - initialMemory.rss,
    heapTotal: finalMemory.heapTotal - initialMemory.heapTotal,
    heapUsed: finalMemory.heapUsed - initialMemory.heapUsed,
    external: finalMemory.external - initialMemory.external
  };

  console.log("Initial heap used:", initialMemory.heapUsed, "bytes");
  console.log("Final heap used:", finalMemory.heapUsed, "bytes");
  console.log("Memory delta:", memoryDelta.heapUsed, "bytes");

  return new Response(JSON.stringify({
    initial: {
      rss: initialMemory.rss,
      heapTotal: initialMemory.heapTotal,
      heapUsed: initialMemory.heapUsed
    },
    final: {
      rss: finalMemory.rss,
      heapTotal: finalMemory.heapTotal,
      heapUsed: finalMemory.heapUsed
    },
    delta: memoryDelta
  }), {
    headers: { "Content-Type": "application/json" }
  });
};

export default main;
```

---

## Example: Uptime and timing

Track process uptime for health monitoring:

```javascript
import process from "node:process";
import { setTimeout } from "node:timers/promises";

const main = async (event) => {
  // Get process uptime in seconds
  const uptime = process.uptime();

  // Get high-resolution time
  const hrtime = process.hrtime();
  const hrtimeBigint = process.hrtime.bigint();

  console.log("Process uptime:", uptime, "seconds");
  console.log("High-res time:", hrtime);
  console.log("High-res time (bigint):", hrtimeBigint.toString(), "nanoseconds");

  // Calculate elapsed time for an operation
  const start = process.hrtime.bigint();

  // Simulate work
  await setTimeout(100);

  const end = process.hrtime.bigint();
  const elapsedNs = Number(end - start);
  const elapsedMs = elapsedNs / 1_000_000;

  console.log("Operation took:", elapsedMs.toFixed(2), "ms");

  return new Response(JSON.stringify({
    uptime: {
      seconds: uptime,
      formatted: formatUptime(uptime)
    },
    hrtime: {
      seconds: hrtime[0],
      nanoseconds: hrtime[1]
    },
    operationTime: {
      nanoseconds: elapsedNs,
      milliseconds: elapsedMs
    }
  }), {
    headers: { "Content-Type": "application/json" }
  });
};

// Helper function defined before export
function formatUptime(seconds) {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);
  return `${hours}h ${minutes}m ${secs}s`;
}

export default main;
```

---

## Supported APIs

| API | Status |
|-----|--------|
| `process.env` | 🟢 Supported |
| `process.nextTick()` | 🟢 Supported |
| `process.platform` | 🟢 Supported |
| `process.arch` | 🟢 Supported |
| `process.version` | 🟢 Supported |
| `process.versions` | 🟢 Supported |
| `process.pid` | 🟢 Supported |
| `process.ppid` | 🟢 Supported |
| `process.uptime()` | 🟢 Supported |
| `process.hrtime()` | 🟢 Supported |
| `process.hrtime.bigint()` | 🟢 Supported |
| `process.memoryUsage()` | 🟢 Supported |
| `process.cwd()` | 🟡 Partially supported |
| `process.exit()` | 🟡 Partially supported |
| `process.on()` | 🟡 Partially supported |
| `process.argv` | 🟡 Partially supported |
| `process.title` | 🟡 Partially supported |

:::note
APIs marked as 🟡 Partially supported have limited functionality compared to the full Node.js implementation. In Azion Runtime, `process.cwd()` returns a fixed path instead of the actual working directory, `process.exit()` doesn't terminate the runtime process, `process.argv` returns a fixed or empty array, and `process.on()` has limited event support. For environment configuration, prefer `process.env` which is fully supported.
:::

---

## Related resources

- [Node.js `process` documentation](https://nodejs.org/api/process.html)