Build a CLI That Scaffolds Projects With Node.js
Build a project scaffolding CLI with util.parseArgs, node:readline prompts, template folders, placeholder replacement and a safe overwrite check.

Every team ends up with a folder of files they copy into each new project: a package.json, a .gitignore, a test setup, a lint config. Copying by hand drifts, and create-* tools from the ecosystem are heavy for what you need. A scaffolder is a small program: read a few answers, copy a template folder, replace placeholders and print what to do next. This post builds one on Node.js 26 with no dependencies, using util.parseArgs for flags, node:readline/promises for prompts, fs.cp for copying and a deliberate overwrite check, so the tool is safe to run in the wrong directory.
The shape of the tool
The command is make-app <name>, with optional flags --template and --yes. If the name is missing the tool asks for it. If --yes is absent it asks a question or two. It copies templates/<template> into ./<name>, replaces tokens such as {{name}} in text files and prints the next steps. The layout is:
make-app/
package.json
bin/make-app.js
templates/
basic/
package.json
README.md
src/index.js
gitignoreNote the template file called gitignore with no dot. Package managers do not publish a file named .gitignore reliably, because npm renames or drops it, so scaffolders store it without the dot and rename it during the copy.
In package.json, the bin field makes the script a command, and "type": "module" allows import.
{
"name": "make-app",
"version": "1.0.0",
"type": "module",
"bin": { "make-app": "bin/make-app.js" },
"files": ["bin", "templates"]
}The first line of bin/make-app.js must be a shebang, #!/usr/bin/env node, so the operating system runs it with Node.js. The file also needs the executable bit, which npm sets when it installs a package with a bin entry, and which you can set while developing with chmod +x bin/make-app.js.
Parsing arguments
util.parseArgs is in the standard library and handles flags, short aliases and positional arguments. It replaces minimist for most tools.
import { parseArgs } from "node:util";
export function readArgs(argv = process.argv.slice(2)) {
const { values, positionals } = parseArgs({
args: argv,
allowPositionals: true,
options: {
template: { type: "string", short: "t", default: "basic" },
yes: { type: "boolean", short: "y", default: false },
help: { type: "boolean", short: "h", default: false },
},
});
return { ...values, name: positionals[0] };
}
console.log(readArgs(["demo", "-t", "basic", "--yes"]));{ template: 'basic', yes: true, help: false, name: 'demo' }By default parseArgs is strict. An unknown flag such as --tempalte throws a TypeError with the code ERR_PARSE_ARGS_UNKNOWN_OPTION, which you should catch and turn into a friendly message, because a raw stack trace is a poor first impression. A typo in a flag name is far more common than any other error in a CLI.
Asking questions
When a value is missing and --yes was not passed, ask. node:readline/promises gives an async interface that reads well in a linear script.
import { createInterface } from "node:readline/promises";
import { stdin, stdout } from "node:process";
export async function ask(question, fallback) {
if (!stdin.isTTY) return fallback;
const rl = createInterface({ input: stdin, output: stdout });
try {
const answer = (await rl.question(`${question} (${fallback}) `)).trim();
return answer || fallback;
} finally {
rl.close();
}
}The isTTY check matters. When the tool runs in a pipeline or a CI job, standard input is not a terminal and a prompt would hang forever. Returning the default in that case makes the same command work interactively and in scripts. Closing the interface in finally also matters: a forgotten rl.close() leaves stdin open and the process never exits.
Validating the name
The project name becomes a directory and a package name, so validate it before touching the disk.
export function checkName(name) {
if (!name) return "a project name is required";
if (!/^[a-z0-9][a-z0-9-_]*$/.test(name)) {
return "use lowercase letters, digits, hyphens and underscores";
}
if (name.length > 214) return "name is longer than npm allows";
return null;
}
console.log(checkName("my-app"));
console.log(checkName("My App"));null
use lowercase letters, digits, hyphens and underscoresRejecting names that start with a dot or contain a slash also blocks a command like make-app ../../etc, which would otherwise write outside the current directory.
Copying and replacing
Node.js 22 stabilized fs.cp, a recursive copy in the standard library, so you no longer need a package for it. The scaffolder copies the template, then walks the result, replaces tokens and renames the dotfile.
import { cp, readdir, readFile, writeFile, rename, stat } from "node:fs/promises";
import { join, extname } from "node:path";
const TEXT = new Set([".json", ".md", ".js", ".txt", ""]);
async function walk(dir) {
const out = [];
for (const entry of await readdir(dir, { withFileTypes: true })) {
const path = join(dir, entry.name);
if (entry.isDirectory()) out.push(...(await walk(path)));
else out.push(path);
}
return out;
}
export async function scaffold({ source, target, tokens }) {
await cp(source, target, { recursive: true, errorOnExist: true, force: false });
for (const file of await walk(target)) {
if (!TEXT.has(extname(file))) continue;
let text = await readFile(file, "utf8");
for (const [key, value] of Object.entries(tokens)) {
text = text.replaceAll(`{{${key}}}`, value);
}
await writeFile(file, text);
}
const ignore = join(target, "gitignore");
try {
await stat(ignore);
await rename(ignore, join(target, ".gitignore"));
} catch (err) {
if (err.code !== "ENOENT") throw err;
}
}The options on cp encode the safety policy: force: false and errorOnExist: true make the copy fail instead of overwriting a file that is already there. The tool also checks the target directory itself before copying, which comes next. Replacement is limited to a list of text extensions, because running replaceAll over a PNG would read it as UTF-8 and corrupt it on write. replaceAll with a string pattern needs no escaping, which avoids the regular expression pitfalls of tokens that contain special characters.
A template file might read:
{
"name": "{{name}}",
"version": "0.1.0",
"type": "module",
"scripts": { "start": "node src/index.js" },
"description": "{{description}}"
}The entry point
Put the pieces together, check the target and print the next steps.
#!/usr/bin/env node
import { access } from "node:fs/promises";
import { resolve } from "node:path";
import { readArgs } from "../lib/args.js";
import { ask } from "../lib/prompt.js";
import { checkName } from "../lib/name.js";
import { scaffold } from "../lib/scaffold.js";
const HELP = `usage: make-app <name> [--template basic] [--yes]`;
let args;
try {
args = readArgs();
} catch (err) {
console.error(`error: ${err.message}\n${HELP}`);
process.exit(2);
}
if (args.help) {
console.log(HELP);
process.exit(0);
}
const name = args.name ?? (await ask("Project name?", "my-app"));
const problem = checkName(name);
if (problem) {
console.error(`error: ${problem}`);
process.exit(2);
}
const description = args.yes ? "A new project" : await ask("Description?", "A new project");
const target = resolve(process.cwd(), name);
const source = new URL(`../templates/${args.template}`, import.meta.url);
try {
await access(source);
} catch {
console.error(`error: unknown template "${args.template}"`);
process.exit(2);
}
try {
await access(target);
console.error(`error: ${name} already exists`);
process.exit(1);
} catch (err) {
if (err.code !== "ENOENT") throw err;
}
await scaffold({ source, target, tokens: { name, description } });
console.log(`Created ${name}\n\n cd ${name}\n npm start`);Exit codes are part of the interface. This tool uses 2 for bad usage, 1 for a refusal and 0 for success, and a script wrapping it can tell them apart. Printing errors to console.error sends them to standard error, so make-app demo > log.txt does not swallow them.
The existence check does not rely on cp failing. Copying into an existing directory merges files, which silently mixes two projects, so the tool refuses up front. That one rule prevents most of the damage a scaffolder can do.
Running it
During development, run the file directly, or link it into your path with npm link from the package folder.
node bin/make-app.js demo --yes
cat demo/package.json
node bin/make-app.js demo --yesCreated demo
cd demo
npm start
{
"name": "demo",
"version": "0.1.0",
"type": "module",
"scripts": { "start": "node src/index.js" },
"description": "A new project"
}
error: demo already existsThe second run exits with status 1 and leaves the first project untouched, which is the behavior you want.
Testing it without a terminal
Because the tool is split into functions, test the pure parts directly, and run the whole binary against a temporary directory for one end-to-end check.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
const run = promisify(execFile);
const bin = new URL("./bin/make-app.js", import.meta.url).pathname;
test("scaffolds a project and replaces tokens", async () => {
const dir = await mkdtemp(join(tmpdir(), "make-app-"));
await run("node", [bin, "demo", "--yes"], { cwd: dir });
const pkg = JSON.parse(await readFile(join(dir, "demo", "package.json"), "utf8"));
assert.equal(pkg.name, "demo");
});
test("refuses to overwrite", async () => {
const dir = await mkdtemp(join(tmpdir(), "make-app-"));
await run("node", [bin, "demo", "--yes"], { cwd: dir });
await assert.rejects(run("node", [bin, "demo", "--yes"], { cwd: dir }), { code: 1 });
});The child process has no TTY, which is exactly the case the prompt helper handles, so the test also covers the non-interactive path.
Design choices that make a CLI pleasant
The code above is the mechanism. What decides whether people keep using the tool is a set of small choices that are easy to get wrong. Start with the help text. A tool that prints nothing useful on --help sends people to read the source, so keep the usage line, the flags and one example in the output, and print it on bad input too, with a nonzero exit code.
Make the defaults match the common case. Here the template defaults to basic, so make-app demo works with no flags. Every required flag you add is a reason someone writes a wrapper script instead.
Be loud about what you did and quiet about everything else. The tool prints the project name and the next two commands, and nothing about copied files unless the user passes a --verbose flag. People read the last lines of output, so put the instruction they need there.
Prefer failing early to failing halfway. Validation of the name, the template and the target directory all happen before the first byte is written. A scaffolder that fails after copying half the files leaves a broken project and a confused user. If a step can fail late, such as an install, run it last and print a clear note that the files were created and only the install failed.
Finally, version your templates with the tool. The files field in package.json ships them together, so version 1.2 of the tool always generates the project it was tested to generate. When templates live in a separate repository that you download at run time, a change to them can break old versions of the CLI without anyone touching the CLI itself, and that bug is miserable to trace.


