by Temi O.

PM2 is a production-grade process manager for Node.js and Bun applications featuring a built-in load balancer, zero-downtime reloads, cluster mode, log management, and startup script generation.
This block is the full PM2 core library (lib/) extracted from user@example.com. It provides programmatic process management, cluster orchestration, module installation, log management, and daemon communication for Node.js and Bun applications. The typical buyer is a backend engineer embedding PM2-style process supervision directly into a Node.js service, toolchain, or deployment platform without relying on the global CLI.
API.js - Main API class; the programmatic entry point for all PM2 operationsClient.js - RPC client that connects to the PM2 daemon over axon socketsCommon.js - Shared CLI utilities: argument normalisation, error formatting, process config resolutionConfiguration.js - Read/write PM2 key-value configuration storeDaemon.js - Daemon bootstrap and lifecycle managementGod.js / God/ - Core process supervisor: fork/cluster modes, reload, action methodsAPI/ - High-level CLI-facing commands (log, serve, deploy, startup, modules, UX)API/Modules/ - Module install/uninstall/package via npm or tarballAPI/UX/ - Terminal rendering: pm2 list, pm2 describe, minimal list, helpersAPI/pm2-plus/ - PM2 Plus (Keymetrics) link, auth strategies, IO integrationbinaries/ - CLI entry points (CLI.js, Runtime.js, Runtime4Docker.js, DevCLI.js)ProcessContainer*.js - Per-process sandbox wrappers for fork and Bun modesProcessUtils.js - Utility functions for process argument and env preparationWatcher.js - File-change watcher (chokidar-based) for --watch modeWorker.js - Background worker cron jobs (e.g. log rotation triggers)Event.js - Internal event bus bridging daemon and clientTreeKill.js - Cross-platform recursive process-tree killUtility.js - Generic helpers (deep-extend, human-readable sizes, etc.)HttpInterface.js - Optional HTTP API surface exposed by the daemonSpin up an isolated sandbox and run it server-side — no local setup.
Tetrees AI Review of this version
This Express backend / api completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Pipeline avcp-2026-08-04.1 · SHA-256 396bde9393d1b5a2…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Reviewed Aug 4, 2026
Push this product straight into your AI IDE, web builder or cloud IDE.
Connect Tetrees to a compatible AI IDE, list products you own, and request the verified ZIP without exposing seller upload controls.
No reviews yet.
Sign in to join the discussion
Loading discussion…
VersionCheck.jscompletion.js / completion.sh - Shell tab-completion supporttemplates/ - Sample app skeletons and init-script templatestools/ - Internal utilities: Config, sexec, which, isbinaryfilenpm install @pm2/agent @pm2/blessed @pm2/io @pm2/js-api @pm2/pm2-version-check \
ansis async chokidar cli-tableau commander croner dayjs debug enquirer \
eventemitter2 fclone js-yaml mkdirp needle pidusage \
pm2-axon pm2-axon-rpc pm2-deploy pm2-multimeter promptly semver
No native build steps, pod installs, or prebuild commands are required. All dependencies are pure JS or ship prebuilt binaries via npm optional dependencies. Node.js >= 12.x or Bun >= 1.x is required at runtime.
source/ directory into your project, e.g. src/pm2-lib/. Also copy constants.js and paths.js from the upstream package root — the library requires both at ../constants.js and ../paths.js relative to source/.package.json.tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
"paths": { "pm2-lib/*": ["src/pm2-lib/*"] }
}
}
require). In an ESM project use dynamic import() or set "esm": false in your bundler config for this subtree.PM2_HOME=~/.pm2 # daemon socket/log/pid directory (default)
PM2_SECRET_KEY=... # optional PM2 Plus secret key
PM2_PUBLIC_KEY=... # optional PM2 Plus public key
PM2_MACHINE_NAME=... # optional PM2 Plus instance label
NODE_ENV=production
API.js — it is the sole public entry point for programmatic use.class API {
constructor(opts?: {
cwd?: string;
pm2_home?: string;
independent?: boolean;
daemon_mode?: boolean;
public_key?: string | null;
secret_key?: string | null;
machine_name?: string | null;
});
connect(noDaemonMode: boolean | ((err: Error, meta: object) => void), cb?: (err: Error, meta: object) => void): void;
disconnect(): void;
start(script: string | object, opts: object, cb?: (err: Error, proc: object) => void): void;
stop(name: string | number, cb?: (err: Error, proc: object) => void): void;
restart(name: string | number, opts: object, cb?: (err: Error, proc: object) => void): void;
delete(name: string | number, cb?: (err: Error, proc: object) => void): void;
list(cb: (err: Error, list: object[]) => void): void;
describe(name: string | number, cb: (err: Error, list: object[]) => void): void;
}
The main class to instantiate. Call connect() before any process operation and disconnect() when done to release the RPC socket. Set daemon_mode: false to run everything in the same process (useful for tests).
function install(
module_name: string,
opts: object,
cb?: (err: Error | null, data: any) => void
): void;
Installs or updates a PM2 module by name. Delegates to Modularizer.install. If no callback is supplied the process list is printed and the CLI exits with success or error code — pass a callback when using programmatically.
function uninstall(
module_name: string,
cb?: (err: Error | null, data: any) => void
): void;
Removes a previously installed PM2 module. Delegates to Modularizer.uninstall. Safe to call at runtime; the module process is stopped before removal.
class Client {
constructor(opts?: {
conf?: object;
daemon_mode?: boolean;
secret_key?: string;
public_key?: string;
machine_name?: string;
});
start(cb: (err: Error | null, meta: object) => void): void;
pingDaemon(cb: (alive: boolean) => void): void;
launchRPC(cb: (err: Error | null, meta: object) => void): void;
disconnectRPC(cb?: () => void): void;
}
Low-level RPC client. Prefer using API in application code. Use Client directly only when building tooling that needs raw daemon communication without the full CLI layer.
Connect to a running PM2 daemon (or spawn one), start a script, list all processes, then cleanly disconnect.
const API = require('./src/pm2-lib/API.js');
const pm2 = new API({ daemon_mode: true });
pm2.connect(false, (err) => {
if (err) { console.error(err); process.exit(1); }
pm2.start('./worker.js', { name: 'my-worker', instances: 2, exec_mode: 'cluster' }, (startErr) => {
if (startErr) console.error('start error', startErr);
pm2.list((listErr, list) => {
if (listErr) console.error(listErr);
else console.log('running processes:', list.map((p: any) => p.name));
pm2.disconnect();
});
});
});
Use the install method exposed on the API class (which mixes in API/Modules/index.js) to add a module such as pm2-logrotate without shelling out.
const API = require('./src/pm2-lib/API.js');
const pm2 = new API();
pm2.connect((err) => {
if (err) throw err;
(pm2 as any).install('pm2-logrotate', { safe: true }, (installErr: Error | null) => {
if (installErr) console.error('install failed', installErr);
else console.log('pm2-logrotate installed successfully');
pm2.disconnect();
});
});
Run processes inside the current process without spawning a separate daemon — useful for integration tests.
const API = require('./src/pm2-lib/API.js');
async function runTest() {
const pm2 = new API({ daemon_mode: false, independent: true });
await new Promise<void>((res, rej) =>
pm2.connect(false, (err) => (err ? rej(err) : res()))
);
await new Promise<void>((res, rej) =>
pm2.start('./echo-server.js', { name: 'echo', env: { PORT: '4000' } },
(err) => (err ? rej(err) : res()))
);
const list: any[] = await new Promise((res, rej) =>
pm2.list((err, l) => (err ? rej(err) : res(l)))
);
console.assert(list.some((p) => p.name === 'echo'), 'process not found');
pm2.disconnect();
}
runTest().catch(console.error);
API class; mixes in all sub-modules from API/; the sole programmatic entry point.PM2_HOME; used by pm2 set/get/unset.ForkMode.js, ClusterMode.js, ActionMethods.js, Methods.js, Reload.js.install, uninstall, launchAll, package — npm and tarball module lifecycle.list, describe, list_min, helpers — blessed/tableau terminal rendering.API.node replacement for container use.@pm2/io, and graceful shutdown.Config (JSON store), sexec (shell exec), which, isbinaryfile.Cannot find module '../constants.js' - The library expects constants.js and paths.js one directory above source/; copy them from the upstream package root alongside source/.PM2_HOME collisions in tests - Multiple test processes sharing the same PM2_HOME corrupt the socket; set independent: true or point each instance to a unique temp directory via pm2_home.require the library - All files use CommonJS module.exports; use createRequire from module or set "type": "commonjs" for this subtree.daemon_mode: false hangs - No-daemon mode still forks child processes; ensure process.exit() is called or all started apps are deleted before test teardown.ansis import errors - The upstream uses ansis not chalk; do not alias or mock chalk — install ansis directly.@pm2/agent peer mismatch - @pm2/agent must match the version range in pm2's own package.json; mismatches cause InteractorClient RPC failures silently at connect time.I have dropped the PM2 core library source into `src/pm2-lib/` in my Node.js
project (upstream package: user@example.com, source from the `lib/` directory).
I also have `constants.js` and `paths.js` from the pm2 package root placed at
`src/constants.js` and `src/paths.js` respectively.
All runtime dependencies from USAGE.md are installed.
Please help me integrate this library step-by-step into my project:
1. Read `src/pm2-lib/API.js` and `src/pm2-lib/Client.js` to understand the
public API surface.
2. Read `USAGE.md` in full for import paths, constructor options, and working
examples.
3. Create a `ProcessManager` service class in `src/services/ProcessManager.ts`
that wraps `API` with async/await helpers for: connect, start, stop,
restart, list, describe, and disconnect.
4. Add error handling that surfaces pm2 daemon errors as typed exceptions.
5. Wire `ProcessManager` into my existing Express app at
`src/app.ts` with graceful shutdown on SIGTERM.
6. Do not invent any API methods — only use symbols visible in API.js,
Client.js, and API/Modules/index.js as documented in USAGE.md.
PM2 is released under the GNU AGPL v3.0 license (see source/LICENSE if present in your copy, or the upstream repository at https://github.com/Unitech/pm2). The upstream npm package is pm2, authored by the PM2 project authors. Commercial use in a closed-source SaaS may require a separate license — consult the upstream repository.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
The full install guide and integration prompts unlock after purchase.
Automation, Utilities & Developer Tools
Free