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,.
Code
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/promisesandreadlineare 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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.