26 lines
1.5 KiB
JavaScript
26 lines
1.5 KiB
JavaScript
// Process sampling and the stop of one process tree. The tool never stops a process by its image name.
|
|
import { execFile } from "node:child_process";
|
|
import { promisify } from "node:util";
|
|
|
|
const run = promisify(execFile);
|
|
|
|
const LIST = "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,PrivatePageCount,WorkingSetSize,@{n='Created';e={if ($_.CreationDate) { $_.CreationDate.ToFileTimeUtc() } else { $null }}} | ConvertTo-Json -Compress";
|
|
|
|
/** List all processes one time, with the private bytes and the working set of each. */
|
|
export async function listProcesses() {
|
|
const { stdout } = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", LIST], { maxBuffer: 64 * 1024 * 1024, windowsHide: true });
|
|
const value = JSON.parse(stdout);
|
|
return (Array.isArray(value) ? value : [value]).map(item => ({ ...item, PrivatePageCount: Number(item.PrivatePageCount ?? 0), WorkingSetSize: Number(item.WorkingSetSize ?? 0) }));
|
|
}
|
|
|
|
/** Stop the process tree of `pid` with taskkill. Errors are returned, not thrown, because the tree can be gone already. */
|
|
export async function stopTree(pid) {
|
|
if (!Number.isInteger(pid) || pid <= 4) throw new Error(`Refusing to stop process ID ${pid}.`);
|
|
try {
|
|
const { stdout } = await run("taskkill.exe", ["/PID", String(pid), "/T", "/F"], { windowsHide: true });
|
|
return { stopped: true, output: stdout.trim() };
|
|
} catch (error) {
|
|
return { stopped: false, output: String(error.stderr || error.message).trim() };
|
|
}
|
|
}
|