or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdfile-system.mdindex.mdnetwork-operations.mdprocess-management.mdshell-execution.mduser-interaction.mdutilities.md

process-management.mddocs/

0

# Process Management

1

2

Advanced process control including promises, output handling, piping, and process lifecycle management through ProcessPromise and ProcessOutput classes.

3

4

## Capabilities

5

6

### ProcessPromise Class

7

8

Extended Promise for handling shell command execution with additional process control methods.

9

10

```typescript { .api }

11

/**

12

* Promise-like class for shell command execution with process control

13

*/

14

class ProcessPromise extends Promise<ProcessOutput> {

15

/** Start the process execution */

16

run(): this;

17

18

/** Kill the process with optional signal */

19

kill(signal?: NodeJS.Signals | null): Promise<void>;

20

21

/** Abort the process execution */

22

abort(reason?: string): void;

23

24

/** Configure whether to throw on non-zero exit codes */

25

nothrow(v?: boolean): this;

26

27

/** Configure output verbosity */

28

quiet(v?: boolean): this;

29

30

/** Configure verbose output */

31

verbose(v?: boolean): this;

32

33

/** Set execution timeout */

34

timeout(d?: Duration, signal?: NodeJS.Signals | undefined): this;

35

36

/** @deprecated Use $({halt: true})`cmd` instead */

37

halt(): this;

38

39

/** Configure standard input/output */

40

stdio(stdin: IOType | StdioOptions, stdout?: IOType, stderr?: IOType): this;

41

}

42

```

43

44

**Process Information Properties:**

45

46

```typescript { .api }

47

class ProcessPromise extends Promise<ProcessOutput> {

48

/** Unique process identifier */

49

get id(): string;

50

51

/** Process ID (available after execution starts) */

52

get pid(): number | undefined;

53

54

/** Command string without arguments */

55

get cmd(): string;

56

57

/** Full command string with arguments */

58

get fullCmd(): string;

59

60

/** Child process instance */

61

get child(): ChildProcess | undefined;

62

63

/** Process execution stage */

64

get stage(): ProcessStage;

65

66

/** Whether execution is synchronous */

67

get sync(): boolean;

68

69

/** Abort signal */

70

get signal(): AbortSignal;

71

72

/** Abort controller */

73

get ac(): AbortController;

74

75

/** Process output (available after completion) */

76

get output(): ProcessOutput | null;

77

}

78

79

type ProcessStage = 'initial' | 'halted' | 'running' | 'fulfilled' | 'rejected';

80

```

81

82

**Stream Access:**

83

84

```typescript { .api }

85

class ProcessPromise extends Promise<ProcessOutput> {

86

/** Standard input stream */

87

get stdin(): Writable;

88

89

/** Standard output stream */

90

get stdout(): Readable;

91

92

/** Standard error stream */

93

get stderr(): Readable;

94

95

/** Promise that resolves with exit code */

96

get exitCode(): Promise<number | null>;

97

}

98

```

99

100

**Output Processing Methods:**

101

102

```typescript { .api }

103

class ProcessPromise extends Promise<ProcessOutput> {

104

/** Parse output as JSON */

105

json<T = any>(): Promise<T>;

106

107

/** Get output as text string */

108

text(encoding?: Encoding): Promise<string>;

109

110

/** Split output into lines */

111

lines(delimiter?: Options['delimiter']): Promise<string[]>;

112

113

/** Get output as Buffer */

114

buffer(): Promise<Buffer>;

115

116

/** Get output as Blob */

117

blob(type?: string): Promise<Blob>;

118

}

119

```

120

121

**State Check Methods:**

122

123

```typescript { .api }

124

class ProcessPromise extends Promise<ProcessOutput> {

125

/** Check if process output is suppressed */

126

isQuiet(): boolean;

127

128

/** Check if verbose output is enabled */

129

isVerbose(): boolean;

130

131

/** Check if process won't throw on errors */

132

isNothrow(): boolean;

133

134

/** Check if process is halted */

135

isHalted(): boolean;

136

}

137

```

138

139

**Usage Examples:**

140

141

```typescript

142

import { $ } from "zx";

143

144

// Basic process control

145

const proc = $`sleep 10`;

146

console.log(proc.id); // Process identifier

147

console.log(proc.pid); // Process PID (after started)

148

149

// Timeout and error handling

150

const result = await $`some-command`

151

.timeout('30s')

152

.nothrow()

153

.quiet();

154

155

// Stream access

156

const longProc = $`tail -f /var/log/system.log`;

157

longProc.stdout.on('data', (chunk) => {

158

console.log('Log:', chunk.toString());

159

});

160

161

// Kill process

162

await longProc.kill('SIGTERM');

163

```

164

165

### ProcessOutput Class

166

167

Result object containing command output, exit information, and processing methods.

168

169

```typescript { .api }

170

/**

171

* Command execution result with output data and metadata

172

*/

173

class ProcessOutput extends Error {

174

/** Exit code (null if killed by signal) */

175

readonly exitCode: number | null;

176

177

/** Signal that killed the process (null if exited normally) */

178

readonly signal: NodeJS.Signals | null;

179

180

/** Standard output content */

181

readonly stdout: string;

182

183

/** Standard error content */

184

readonly stderr: string;

185

186

/** Combined stdout and stderr */

187

readonly stdall: string;

188

189

/** Execution duration in milliseconds */

190

readonly duration: number;

191

192

/** Whether command succeeded (exit code 0) */

193

readonly ok: boolean;

194

195

/** Error message */

196

readonly message: string;

197

198

/** Cause error (if any) */

199

readonly cause: Error | null;

200

}

201

```

202

203

**Output Processing Methods:**

204

205

```typescript { .api }

206

class ProcessOutput extends Error {

207

/** Parse stdout as JSON */

208

json<T = any>(): T;

209

210

/** Get stdout as text with optional encoding */

211

text(encoding?: Encoding): string;

212

213

/** Split stdout into lines */

214

lines(delimiter?: string | RegExp): string[];

215

216

/** Get stdout as Buffer */

217

buffer(): Buffer;

218

219

/** Get stdout as Blob */

220

blob(type?: string): Blob;

221

222

/** String representation (returns stdout) */

223

toString(): string;

224

225

/** Primitive value (returns stdout) */

226

valueOf(): string;

227

228

/** Iterator over lines */

229

[Symbol.iterator](dlmtr?: Options['delimiter']): Iterator<string>;

230

}

231

```

232

233

**Static Methods:**

234

235

```typescript { .api }

236

class ProcessOutput extends Error {

237

/** Format exit error message */

238

static getExitMessage: typeof Fail.formatExitMessage;

239

240

/** Format general error message */

241

static getErrorMessage: typeof Fail.formatErrorMessage;

242

243

/** Format error details */

244

static getErrorDetails: typeof Fail.formatErrorDetails;

245

246

/** Get exit code information */

247

static getExitCodeInfo: typeof Fail.getExitCodeInfo;

248

249

/** Create ProcessOutput from generic Error */

250

static fromError(error: Error): ProcessOutput;

251

}

252

```

253

254

**Usage Examples:**

255

256

```typescript

257

import { $ } from "zx";

258

259

// Basic output handling

260

const result = await $`ls -la`;

261

console.log(result.stdout); // File listing

262

console.log(result.exitCode); // 0 for success

263

console.log(result.ok); // true for success

264

265

// Error handling

266

try {

267

await $`false`; // Command that always fails

268

} catch (error) {

269

if (error instanceof ProcessOutput) {

270

console.log('Exit code:', error.exitCode);

271

console.log('stderr:', error.stderr);

272

console.log('Duration:', error.duration, 'ms');

273

}

274

}

275

276

// JSON parsing

277

const packageInfo = await $`cat package.json`;

278

const pkg = packageInfo.json();

279

console.log(pkg.name);

280

281

// Line processing

282

const logLines = await $`tail -n 10 /var/log/system.log`;

283

for (const line of logLines.lines()) {

284

console.log('Log line:', line);

285

}

286

```

287

288

### Process Piping

289

290

Connect processes together using Unix-style piping.

291

292

```typescript { .api }

293

interface ProcessPromise extends Promise<ProcessOutput> {

294

/** Pipe output to another command or stream */

295

get pipe(): PipeMethod & {

296

[key in keyof TSpawnStore]: PipeMethod;

297

};

298

299

/** Remove piping connection */

300

unpipe(to?: PipeAcceptor): this;

301

}

302

303

type PipeMethod = {

304

/** Pipe to shell command */

305

(dest: TemplateStringsArray, ...args: any[]): ProcessPromise;

306

/** Pipe to file */

307

(file: string): PromisifiedStream;

308

/** Pipe to writable stream */

309

<D extends Writable>(dest: D): PromisifiedStream<D>;

310

/** Pipe to another ProcessPromise */

311

<D extends ProcessPromise>(dest: D): D;

312

};

313

314

type PipeAcceptor = Writable | ProcessPromise;

315

316

type PromisifiedStream<D extends Writable = Writable> =

317

D & PromiseLike<ProcessOutput & D> & {

318

run(): void;

319

};

320

```

321

322

**Usage Examples:**

323

324

```typescript

325

import { $ } from "zx";

326

import fs from "fs";

327

328

// Pipe to another command

329

const result = await $`cat /etc/passwd`

330

.pipe`grep root`

331

.pipe`wc -l`;

332

333

// Pipe to file

334

await $`echo "Hello World"`

335

.pipe('./output.txt');

336

337

// Pipe to stream

338

const writeStream = fs.createWriteStream('./data.txt');

339

await $`ls -la`.pipe(writeStream);

340

341

// Complex piping

342

await $`find /var/log -name "*.log"`

343

.pipe`head -10`

344

.pipe`sort`

345

.pipe('./sorted-logs.txt');

346

```

347

348

### Async Iteration

349

350

Process output as an async iterator for streaming data processing.

351

352

```typescript { .api }

353

interface ProcessPromise extends Promise<ProcessOutput> {

354

/** Async iterator over output lines */

355

[Symbol.asyncIterator](): AsyncIterator<string>;

356

}

357

```

358

359

**Usage:**

360

361

```typescript

362

import { $ } from "zx";

363

364

// Stream processing

365

const proc = $`tail -f /var/log/system.log`;

366

367

for await (const line of proc) {

368

console.log('New log line:', line);

369

370

if (line.includes('ERROR')) {

371

proc.kill();

372

break;

373

}

374

}

375

```

376

377

## Types

378

379

```typescript { .api }

380

type Duration = string | number;

381

382

type IOType = 'pipe' | 'ignore' | 'inherit';

383

384

type StdioOptions = IOType | Array<IOType | Stream | number | null | undefined>;

385

386

type Encoding = BufferEncoding;

387

388

interface TSpawnStore {

389

[key: string]: any;

390

}

391

```