or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Optimist

1

2

Optimist is a lightweight command-line argument parsing library for Node.js applications. It provides an intuitive API for parsing process.argv with support for short and long options, boolean flags, default values, aliases, and automatic help generation, making it easy to create command-line interfaces without complex configuration.

3

4

## Package Information

5

6

- **Package Name**: optimist

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install optimist`

10

11

## Core Imports

12

13

```javascript

14

var optimist = require('optimist');

15

var argv = optimist.argv;

16

```

17

18

Direct argv access:

19

20

```javascript

21

var argv = require('optimist').argv;

22

```

23

24

## Basic Usage

25

26

```javascript

27

#!/usr/bin/env node

28

var argv = require('optimist').argv;

29

30

if (argv.rif - 5 * argv.xup > 7.138) {

31

console.log('Buy more riffiwobbles');

32

}

33

else {

34

console.log('Sell the xupptumblers');

35

}

36

```

37

38

More comprehensive example with configuration:

39

40

```javascript

41

var optimist = require('optimist');

42

43

var argv = optimist

44

.usage('Usage: $0 -f [file] -p [port]')

45

.demand(['f'])

46

.alias('f', 'file')

47

.alias('p', 'port')

48

.default('p', 3000)

49

.describe('f', 'Input file path')

50

.describe('p', 'Server port number')

51

.boolean('verbose')

52

.argv;

53

54

console.log('File:', argv.file);

55

console.log('Port:', argv.port);

56

console.log('Verbose:', argv.verbose);

57

```

58

59

## Architecture

60

61

Optimist uses a simple architecture centered around:

62

63

- **Main Instance**: Pre-configured parser instance with bound methods

64

- **Method Chaining**: Fluent API where configuration methods return the instance

65

- **Lazy Parsing**: Arguments are parsed when `.argv` property is accessed

66

- **Configuration State**: Internal state tracks options, defaults, aliases, and validation rules

67

68

## Capabilities

69

70

### Core Argument Parsing

71

72

The fundamental parsed arguments object containing all command-line parameters.

73

74

```javascript { .api }

75

/**

76

* Parsed command-line arguments object with proper keys set

77

* @type {Object}

78

*/

79

argv

80

```

81

82

### Custom Argument Parsing

83

84

Parse a specific arguments array instead of process.argv.

85

86

```javascript { .api }

87

/**

88

* Parse provided args array instead of process.argv

89

* @param {Array} args - Arguments array to parse

90

* @returns {Object} Parsed arguments object

91

*/

92

.parse(args)

93

```

94

95

**Usage Example:**

96

97

```javascript

98

var optimist = require('optimist');

99

var args = ['--verbose', '--file', 'input.txt', '--port', '8080'];

100

var parsed = optimist.parse(args);

101

console.log(parsed); // { verbose: true, file: 'input.txt', port: 8080, _: [] }

102

```

103

104

### Option Configuration

105

106

Configure individual options with detailed specifications.

107

108

```javascript { .api }

109

/**

110

* Set a key with options configuration

111

* @param {string} key - Option key name

112

* @param {Object} opt - Option configuration object

113

* @returns {Object} Optimist instance for chaining

114

*/

115

.option(key, opt)

116

```

117

118

**Usage Example:**

119

120

```javascript

121

var argv = require('optimist')

122

.option('f', {

123

alias: 'file',

124

demand: true,

125

default: 'input.txt',

126

describe: 'Input file path',

127

type: 'string'

128

})

129

.argv;

130

```

131

132

### Usage Message Configuration

133

134

Set a usage message for help output display.

135

136

```javascript { .api }

137

/**

138

* Set a usage message for help output

139

* @param {string} message - Usage message text

140

* @returns {Object} Optimist instance for chaining

141

*/

142

.usage(message)

143

```

144

145

**Usage Example:**

146

147

```javascript

148

var argv = require('optimist')

149

.usage('Usage: $0 [options]')

150

.usage('Process files with various options')

151

.argv;

152

```

153

154

### Required Arguments

155

156

Demand that particular keys exist in the parsed arguments.

157

158

```javascript { .api }

159

/**

160

* Demand that particular keys exist in arguments

161

* @param {string|Array} key - Required key name(s)

162

* @returns {Object} Optimist instance for chaining

163

*/

164

.demand(key)

165

```

166

167

**Usage Example:**

168

169

```javascript

170

var argv = require('optimist')

171

.demand(['input', 'output'])

172

.demand('config')

173

.argv;

174

// Will exit with error if input, output, or config are not provided

175

```

176

177

### Default Values

178

179

Set default values for command-line options.

180

181

```javascript { .api }

182

/**

183

* Set default values for particular keys

184

* @param {string} key - Option key name

185

* @param {*} value - Default value (any type)

186

* @returns {Object} Optimist instance for chaining

187

*/

188

.default(key, value)

189

```

190

191

**Usage Example:**

192

193

```javascript

194

var argv = require('optimist')

195

.default('port', 3000)

196

.default('host', 'localhost')

197

.default('verbose', false)

198

.argv;

199

```

200

201

### Boolean Type Interpretation

202

203

Interpret specified keys as boolean values.

204

205

```javascript { .api }

206

/**

207

* Interpret a key as a boolean value

208

* @param {string|Array} key - Key name(s) to treat as boolean

209

* @returns {Object} Optimist instance for chaining

210

*/

211

.boolean(key)

212

```

213

214

**Usage Example:**

215

216

```javascript

217

var argv = require('optimist')

218

.boolean(['verbose', 'debug', 'force'])

219

.argv;

220

// --verbose becomes true, --no-verbose becomes false

221

```

222

223

### String Type Interpretation

224

225

Force specified keys to be interpreted as strings, preventing numeric coercion.

226

227

```javascript { .api }

228

/**

229

* Tell parser not to interpret key as number or boolean

230

* @param {string|Array} key - Key name(s) to treat as string

231

* @returns {Object} Optimist instance for chaining

232

*/

233

.string(key)

234

```

235

236

**Usage Example:**

237

238

```javascript

239

var argv = require('optimist')

240

.string(['id', 'version'])

241

.argv;

242

// --id 001 remains "001" instead of becoming 1

243

```

244

245

### Help Text Formatting

246

247

Configure text wrapping for help output display.

248

249

```javascript { .api }

250

/**

251

* Format usage output to wrap at specified columns

252

* @param {number} columns - Number of columns for text wrapping

253

* @returns {Object} Optimist instance for chaining

254

*/

255

.wrap(columns)

256

```

257

258

**Usage Example:**

259

260

```javascript

261

var optimist = require('optimist')

262

.wrap(80)

263

.describe('very-long-option-name', 'This is a very long description that will be wrapped at 80 columns for better readability in terminal output');

264

```

265

266

### Help Text Generation

267

268

Generate formatted help text string.

269

270

```javascript { .api }

271

/**

272

* Return the generated usage string

273

* @returns {string} Formatted help text

274

*/

275

.help()

276

```

277

278

**Usage Example:**

279

280

```javascript

281

var optimist = require('optimist')

282

.usage('Usage: $0 [options]')

283

.describe('input', 'Input file path')

284

.describe('output', 'Output file path');

285

286

console.log(optimist.help());

287

```

288

289

### Help Text Display

290

291

Print usage information using a specified output function.

292

293

```javascript { .api }

294

/**

295

* Print usage data using specified function

296

* @param {Function} [fn=console.error] - Function for printing help text

297

* @returns {Object} Optimist instance for chaining

298

*/

299

.showHelp(fn)

300

```

301

302

**Usage Example:**

303

304

```javascript

305

var optimist = require('optimist')

306

.usage('Usage: $0 [options]')

307

.describe('help', 'Show help information');

308

309

if (argv.help) {

310

optimist.showHelp(console.log); // Use console.log instead of console.error

311

process.exit(0);

312

}

313

```

314

315

### Option Aliases

316

317

Create alternative names for command-line options.

318

319

```javascript { .api }

320

/**

321

* Set an alias for a key

322

* @param {string} key - Original key name

323

* @param {string} alias - Alias name

324

* @returns {Object} Optimist instance for chaining

325

*/

326

.alias(key, alias)

327

```

328

329

**Usage Example:**

330

331

```javascript

332

var argv = require('optimist')

333

.alias('f', 'file')

334

.alias('p', 'port')

335

.alias('v', 'verbose')

336

.argv;

337

// Both -f and --file will set the 'file' property

338

```

339

340

### Option Descriptions

341

342

Add descriptive text for options in help output.

343

344

```javascript { .api }

345

/**

346

* Describe a key for generated usage information

347

* @param {string} key - Option key name

348

* @param {string} desc - Description text

349

* @returns {Object} Optimist instance for chaining

350

*/

351

.describe(key, desc)

352

```

353

354

**Usage Example:**

355

356

```javascript

357

var argv = require('optimist')

358

.describe('input', 'Path to the input file')

359

.describe('output', 'Path to the output file')

360

.describe('verbose', 'Enable verbose logging')

361

.argv;

362

```

363

364

### Custom Validation

365

366

Implement custom validation logic for parsed arguments.

367

368

```javascript { .api }

369

/**

370

* Check that certain conditions are met in provided arguments

371

* @param {Function} fn - Validation function that throws on failure

372

* @returns {Object} Optimist instance for chaining

373

*/

374

.check(fn)

375

```

376

377

**Usage Example:**

378

379

```javascript

380

var argv = require('optimist')

381

.check(function(argv) {

382

if (argv._.length === 0) {

383

throw new Error('At least one input file is required');

384

}

385

if (argv.port && (argv.port < 1 || argv.port > 65535)) {

386

throw new Error('Port must be between 1 and 65535');

387

}

388

})

389

.argv;

390

```

391

392

## Common Patterns

393

394

### Configuration-Heavy CLI Tools

395

396

```javascript

397

var optimist = require('optimist');

398

399

var argv = optimist

400

.usage('Usage: $0 [options]')

401

.option('config', {

402

alias: 'c',

403

describe: 'Configuration file path',

404

type: 'string'

405

})

406

.option('verbose', {

407

alias: 'v',

408

describe: 'Enable verbose output',

409

type: 'boolean',

410

default: false

411

})

412

.option('port', {

413

alias: 'p',

414

describe: 'Server port',

415

type: 'number',

416

default: 3000

417

})

418

.demand(['config'])

419

.check(function(argv) {

420

if (!require('fs').existsSync(argv.config)) {

421

throw new Error('Configuration file does not exist: ' + argv.config);

422

}

423

})

424

.argv;

425

```

426

427

### Simple Utility Scripts

428

429

```javascript

430

var argv = require('optimist')

431

.boolean('dry-run')

432

.default('format', 'json')

433

.string(['input', 'output'])

434

.argv;

435

436

if (argv['dry-run']) {

437

console.log('Dry run mode - no changes will be made');

438

}

439

```

440

441

## Error Handling

442

443

Optimist will automatically exit the process with an error message when:

444

- Required arguments (via `.demand()`) are missing

445

- Custom validation (via `.check()`) fails

446

- Invalid usage patterns are detected

447

448

To handle errors gracefully in your application, wrap optimist usage in try-catch blocks or use `.parse()` instead of `.argv` for more control over error handling.