or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-zx

A tool for writing better scripts by bridging JavaScript and shell commands with cross-platform wrappers around child_process

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/zx@8.8.x

To install, run

npx @tessl/cli install tessl/npm-zx@8.8.0

0

# ZX - A Tool for Writing Better Scripts

1

2

ZX provides useful cross-platform wrappers around Node.js `child_process`, enabling developers to write more complex automation scripts with the convenience of JavaScript while maintaining direct access to shell operations. It bridges JavaScript and shell commands with automatic argument escaping, sensible defaults, and Promise-based asynchronous execution.

3

4

## Package Information

5

6

- **Package Name**: zx

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install zx`

10

- **Runtime Support**: Node.js >= 12.17.0, Bun >= 1.0.0, Deno 1.x/2.x, GraalVM Node.js

11

- **Platform Support**: Linux, macOS, Windows

12

13

## Core Imports

14

15

```typescript

16

import { $ } from "zx";

17

```

18

19

For CommonJS:

20

21

```javascript

22

const { $ } = require("zx");

23

```

24

25

For global script usage:

26

27

```typescript

28

import "zx/globals";

29

// Now $ and all other functions are available globally

30

```

31

32

## Basic Usage

33

34

```typescript

35

import { $, echo, sleep } from "zx";

36

37

// Execute shell commands

38

const result = await $`echo "Hello World"`;

39

echo`Server response: ${result}`;

40

41

// With configuration

42

const output = await $({ quiet: true })`git status`;

43

44

// Concurrent execution

45

await Promise.all([

46

$`sleep 1; echo 1`,

47

$`sleep 2; echo 2`,

48

$`sleep 3; echo 3`,

49

]);

50

51

// Safe argument handling

52

const name = 'foo bar';

53

await $`mkdir /tmp/${name}`;

54

```

55

56

## Architecture

57

58

ZX is built around several key components:

59

60

- **Shell Interface**: The `$` function for executing shell commands with configuration options

61

- **Process Management**: `ProcessPromise` and `ProcessOutput` classes for handling command execution and results

62

- **Utility Functions**: Common scripting operations like file handling, user interaction, and retry logic

63

- **Cross-platform Support**: Automatic shell detection and platform-specific optimizations

64

- **Global Mode**: Optional global variable declarations for script-style usage

65

66

## Capabilities

67

68

### Shell Execution

69

70

Core shell command execution with the `$` function, process management, and output handling.

71

72

```typescript { .api }

73

interface Shell<S = false, R = S extends true ? ProcessOutput : ProcessPromise> {

74

(pieces: TemplateStringsArray, ...args: any[]): R;

75

<O extends Partial<Options>>(opts: O): Shell;

76

sync: Shell<true>;

77

}

78

79

type $ = Shell & Options;

80

declare const $: $;

81

```

82

83

[Shell Execution](./shell-execution.md)

84

85

### Process Management

86

87

Advanced process control including promises, output handling, piping, and process lifecycle management.

88

89

```typescript { .api }

90

class ProcessPromise extends Promise<ProcessOutput> {

91

run(): this;

92

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

93

abort(reason?: string): void;

94

nothrow(v?: boolean): this;

95

quiet(v?: boolean): this;

96

verbose(v?: boolean): this;

97

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

98

99

get pid(): number | undefined;

100

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

101

get stdin(): Writable;

102

get stdout(): Readable;

103

get stderr(): Readable;

104

105

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

106

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

107

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

108

buffer(): Promise<Buffer>;

109

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

110

}

111

112

class ProcessOutput extends Error {

113

readonly exitCode: number | null;

114

readonly signal: NodeJS.Signals | null;

115

readonly stdout: string;

116

readonly stderr: string;

117

readonly stdall: string;

118

readonly duration: number;

119

readonly ok: boolean;

120

121

json<T = any>(): T;

122

text(encoding?: Encoding): string;

123

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

124

buffer(): Buffer;

125

blob(type?: string): Blob;

126

}

127

```

128

129

[Process Management](./process-management.md)

130

131

### File System Operations

132

133

File and directory manipulation utilities for temporary files, directory navigation, and file system operations.

134

135

```typescript { .api }

136

function tempdir(prefix?: string, mode?: Mode): string;

137

function tempfile(name?: string, data?: string | Buffer, mode?: Mode): string;

138

function cd(dir: string | ProcessOutput): void;

139

140

// Re-exports

141

export { default as path } from "node:path";

142

export * as os from "node:os";

143

export { fs } from "./vendor";

144

```

145

146

[File System Operations](./file-system.md)

147

148

### User Interaction

149

150

Interactive utilities for user input, output formatting, and visual feedback.

151

152

```typescript { .api }

153

function echo(...args: any[]): void;

154

function question(

155

query?: string,

156

options?: {

157

choices?: string[];

158

input?: NodeJS.ReadStream;

159

output?: NodeJS.WriteStream;

160

}

161

): Promise<string>;

162

function stdin(stream?: Readable): Promise<string>;

163

function spinner<T>(title: string, callback: () => T): Promise<T>;

164

```

165

166

[User Interaction](./user-interaction.md)

167

168

### Network Operations

169

170

HTTP operations with fetch API and piping support for data streaming.

171

172

```typescript { .api }

173

function fetch(

174

url: RequestInfo,

175

init?: RequestInit

176

): Promise<Response> & {

177

pipe: {

178

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

179

<D>(dest: D): D;

180

};

181

};

182

```

183

184

[Network Operations](./network-operations.md)

185

186

### Utility Functions

187

188

General-purpose utilities for common scripting tasks including argument parsing, retry logic, and async utilities.

189

190

```typescript { .api }

191

function sleep(duration: Duration): Promise<void>;

192

function retry<T>(count: number, callback: () => T): Promise<T>;

193

function retry<T>(

194

count: number,

195

duration: Duration | Generator<number>,

196

callback: () => T

197

): Promise<T>;

198

function expBackoff(max?: Duration, delay?: Duration): Generator<number>;

199

function parseArgv(

200

args?: string[],

201

opts?: ArgvOpts,

202

defs?: Record<string, any>

203

): minimist.ParsedArgs;

204

205

declare const argv: minimist.ParsedArgs;

206

```

207

208

[Utility Functions](./utilities.md)

209

210

### CLI Functions

211

212

Command line interface specific functionality available from zx/cli import.

213

214

```typescript { .api }

215

function transformMarkdown(content: string): string;

216

```

217

218

[CLI Functions](./cli.md)

219

220

### Version Information

221

222

Access to package version and dependency information.

223

224

```typescript { .api }

225

declare const VERSION: string;

226

declare const version: string;

227

declare const versions: Record<string, string>;

228

```

229

230

## Types

231

232

```typescript { .api }

233

interface Options {

234

cwd?: string;

235

env?: NodeJS.ProcessEnv;

236

shell?: string | true;

237

stdio?: StdioOptions;

238

verbose?: boolean;

239

quiet?: boolean;

240

nothrow?: boolean;

241

timeout?: Duration;

242

timeoutSignal?: NodeJS.Signals;

243

killSignal?: NodeJS.Signals;

244

prefix?: string;

245

postfix?: string;

246

detached?: boolean;

247

preferLocal?: boolean | string | string[];

248

sync?: boolean;

249

input?: string | Buffer | Readable | ProcessOutput | ProcessPromise;

250

signal?: AbortSignal;

251

ac?: AbortController;

252

}

253

254

type Duration = string | number;

255

256

interface ArgvOpts extends minimist.Opts {

257

camelCase?: boolean;

258

parseBoolean?: boolean;

259

}

260

261

/**

262

* Chalk instance for terminal string styling

263

*/

264

interface ChalkInstance {

265

(text: string): string;

266

// Color functions

267

black: ChalkInstance;

268

red: ChalkInstance;

269

green: ChalkInstance;

270

yellow: ChalkInstance;

271

blue: ChalkInstance;

272

magenta: ChalkInstance;

273

cyan: ChalkInstance;

274

white: ChalkInstance;

275

gray: ChalkInstance;

276

// Style functions

277

bold: ChalkInstance;

278

dim: ChalkInstance;

279

italic: ChalkInstance;

280

underline: ChalkInstance;

281

strikethrough: ChalkInstance;

282

// Background colors

283

bgBlack: ChalkInstance;

284

bgRed: ChalkInstance;

285

bgGreen: ChalkInstance;

286

bgYellow: ChalkInstance;

287

bgBlue: ChalkInstance;

288

bgMagenta: ChalkInstance;

289

bgCyan: ChalkInstance;

290

bgWhite: ChalkInstance;

291

}

292

293

/**

294

* YAML parsing and serialization interface

295

*/

296

interface YAML {

297

parse(text: string): any;

298

stringify(object: any): string;

299

}

300

301

/**

302

* Glob options for file pattern matching

303

*/

304

interface GlobbyOptions {

305

absolute?: boolean;

306

baseNameMatch?: boolean;

307

braceExpansion?: boolean;

308

caseSensitiveMatch?: boolean;

309

concurrency?: number;

310

cwd?: string;

311

deep?: number;

312

dot?: boolean;

313

expandDirectories?: boolean;

314

extglob?: boolean;

315

followSymbolicLinks?: boolean;

316

gitignore?: boolean;

317

globstar?: boolean;

318

ignore?: string[];

319

markDirectories?: boolean;

320

objectMode?: boolean;

321

onlyDirectories?: boolean;

322

onlyFiles?: boolean;

323

stats?: boolean;

324

suppressErrors?: boolean;

325

throwErrorOnBrokenSymbolicLink?: boolean;

326

unique?: boolean;

327

}

328

329

/**

330

* HTTP request types

331

*/

332

type RequestInfo = string | URL;

333

interface RequestInit {

334

method?: string;

335

headers?: HeadersInit;

336

body?: BodyInit | null;

337

signal?: AbortSignal;

338

redirect?: RequestRedirect;

339

referrer?: string;

340

referrerPolicy?: ReferrerPolicy;

341

mode?: RequestMode;

342

credentials?: RequestCredentials;

343

cache?: RequestCache;

344

integrity?: string;

345

keepalive?: boolean;

346

window?: any;

347

}

348

```