Vanilla JavaScript CLI Script

Build a command-line utility in vanilla JavaScript using process.argv parsing, readline for interactive prompts, chalk-free colored output with ANSI codes,.

JavascriptCli Tooling

Code

snippet
import { readFile, writeFile } from 'fs/promises';
import { createInterface } from 'readline';

const args = Object.fromEntries(
  process.argv.slice(2).map((a) => {
    const [k, v] = a.split('=');
    return [k.replace('--', ''), v ?? true];
  }),
);

const rl = createInterface({ input: process.stdin, output: process.stdout });
const ask = (q) => new Promise((r) => rl.question(q, r));

const name = args.name ?? (await ask('Project name: '));
await writeFile(`${name}/package.json`, JSON.stringify({ name }, null, 2));
rl.close();

How the snippet works

Vanilla JavaScript CLI Script comes down to the function ask.

Await points sequence the asynchronous work; a rejection lands at the awaiting line. The snippet’s external surface is readFile, writeFile, createInterface, all of it via fs/promises.

A fresh value is allocated for the result; the arguments stay untouched.

Points of care

  • Plan for an install step: fs/promises and readline are a real dependency, resolved by the package manager.

Using it

The primary signature is const ask = (q)

Key statements

await writeFile(`${name}/package.json`, JSON.stringify({ name }, null, 2));
const ask = (q) => new Promise((r) => rl.question(q, r));
const name = args.name ?? (await ask('Project name: '));

Interactive Tools for This Topic

FAQ

Does `ask` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
What does this need from the package registry?
These are real dependencies: `fs/promises` and `readline`. Without them the snippet will not load.