Skip to content

Repository files navigation

script-journal

Run a task module in a child process, persist JSON status, and capture NDJSON logs. Host apps only author tasks; this library owns execution, status, and log I/O.

Works from both ESM and CommonJS consumers. Task files may be .mjs, .js, or .cjs.

Other languages: 中文 | Deutsch | Español | Français | 日本語

Installation

npm install script-journal

Quick start

import { runTask, stopTask, readTaskJson, readTaskLog } from "script-journal";

try {
  const state = await runTask({
    cwd: "/path/to/your-app", // optional, default process.cwd()
    task: "src/tasks/helloTask.mjs", // absolute or relative to cwd
    output: "tmp/tasks/hello", // absolute or relative to cwd (no extension)
    parameters: { name: "world" },
  });
  // state is the task JSON (status: "done", ...)
} catch (state) {
  // on failure, the same JSON object is thrown (error already written to file)
  console.error(state.error);
}

// Force-stop a running task by its output path (kills pid from JSON if still alive)
await stopTask({ cwd: "/path/to/your-app", output: "tmp/tasks/hello" });

const persisted = readTaskJson({
  cwd: "/path/to/your-app",
  output: "tmp/tasks/hello",
});

// Defaults to tail=true (latest pages). totalLines is bounded by maxLogLines.
const log = readTaskLog({
  cwd: "/path/to/your-app",
  output: "tmp/tasks/hello",
  pageSize: 50,
});

CommonJS:

const { runTask, stopTask, readTaskJson, readTaskLog } = require("script-journal");

Parent process stays silent: child stdout/stderr are captured into the log file only.

Task module contract

// src/tasks/helloTask.mjs
export async function run(parameters, ctx) {
  ctx.logger.info("hello started");
  ctx.patchResults({ total: 0, failed: 0 });

  // ... work using parameters ...

  ctx.patchResults({ total: 3 });
  return { success: true }; // or { success: false, error: "..." }
}

ctx

Field Description
logger.debug/info/warn/error(msg) Writes [LEVEL] msg; captured into NDJSON log
results Current results object (shared reference)
updateResults(patch) Shallow-merge into results and persist JSON
patchResults(patch) Same merge, returns results

Return value

  • undefined / null — keep results accumulated via patchResults
  • object — shallow-merged into results; success decides done/failed; errorstate.error

Exit code: 0 if success, else 1.

Status JSON

Written to <output>.json:

{
  "task": "/abs/path/to/helloTask.mjs",
  "status": "pending|running|done|failed|error|stopped",
  "pid": 12345,
  "startedAt": "ISO|null",
  "finishedAt": "ISO|null",
  "durationMs": 0,
  "success": true,
  "parameters": {},
  "error": null,
  "results": {}
}

pid is set while the runner is alive and cleared (null) when the task finishes or is stopped.

Log file

<output>.log — one NDJSON object per line:

{"timestamp":"2026-07-19T01:00:00.000Z","level":"info","message":"hello started"}

When the log exceeds maxLogLines (default 10000), older lines are deleted from the head so only the newest lines remain. Pass maxLogLines: 0 to disable trimming.

API

runTask(options)

Field Type Required Description
cwd string Working directory, default process.cwd()
task string Task file path (absolute or relative to cwd)
output string Output base path without extension (absolute or relative to cwd)
parameters object Passed to run(parameters, ctx)
maxLogLines number Max retained log lines; older lines dropped from head. Default 10000. ≤0 disables

Before writing a new pending state, runTask reads any existing <output>.json and force-terminates a still-alive pid (if present). This prevents orphan runners when the same output is reused.

Returns the task JSON state on success. On failure, rejects with that same JSON object (error is already persisted to <output>.json).

Windows: process liveness uses tasklist; termination uses taskkill /T /F (process tree). Spawn uses windowsHide: true. Runner SIGTERM handlers are not invoked by taskkill /F; stopTask still writes status: "stopped" in the parent after kill.

stopTask({ cwd?, output })

Force-stop the task for output: terminate a live pid from <output>.json, then write status: "stopped", success: false, pid: null. Idempotent if the process is already gone. Throws if the state file is missing.

readTaskJson({ cwd?, output }) / readTaskLog({ cwd?, output, page?, pageSize?, tail? })

Same cwd / output resolution rules as runTask.

readTaskLog defaults to tail: true (latest pages). Set tail: false to read from the start.

License

MIT

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages