Building a Simple Node.js CLI Generator in Five Steps
This tutorial explains how to create a Node.js command‑line generator from scratch by initializing a module, adding a CLI binary, integrating a template engine, parsing arguments and paths, and finally publishing the package to npm, all with clear code examples.
Node.js makes writing generators easy because its module system uses plain JavaScript, npm provides the simplest package manager, and there are nearly 400 000 auxiliary modules available.
To help beginners create a generator in ten minutes, the process is broken down into five steps.
1) Initialize the module
Choose a package name, create a Git repository, and run $ git clone xxx followed by $ npm init -y to generate a package.json file. The most important fields are "main" (the entry file) and "scripts" for npm commands.
2) CLI binary module
Generators are CLI tools, so add a bin entry in package.json :
{
"name": "a",
"version": "1.0.0",
"main": "index.js",
"bin": { "gen": "gen.js" },
"scripts": { "test": "echo \"Error: no test specified\" && exit 1" }
}Create gen.js with a shebang and basic logging:
#!/usr/bin/env node
var argv = process.argv;
var filePath = __dirname;
var currentPath = process.cwd();
console.log(argv);
console.log(filePath);
console.log(currentPath);Install the binary locally with $ npm link and test it using $ gen , which prints the argument array and path variables.
3) Template engine usage
Use a template engine to separate static code from dynamic data. The tutorial chooses Nunjucks and installs it with $ npm install --save nunjucks . A simple render example:
var nunjucks = require('nunjucks');
var compiledData = nunjucks.renderString('Hello {{ username }}', { username: 'James' });
console.log(compiledData);Read a template file gen.tpl (e.g., Hello {{ username }} ) using fs.readFileSync , render it with data, and write the result to gen.xxx :
var fs = require('fs');
var tpl = fs.readFileSync('./gen.tpl').toString();
var compiledData = nunjucks.renderString(tpl, { username: 'James' });
fs.writeFileSync('./gen.xxx', compiledData);4) Parse CLI arguments and paths
Implement a Rails‑style scaffold command such as $ gen book name:string coordinates:string . The script parses process.argv , builds an object like:
var data = {
model: argv[0],
attr: { name: 'string', coordinates: 'string' }
};Then read the template from __dirname , render it with the data object, and write the output to the current working directory ( process.cwd() ).
5) Publish to npm
After testing, publish the package with $ npm publish . . To release a new version, bump the version using $ npm version patch and publish again. Users can install the generator globally with $ npm i -g xxxxxx and share it with others.
The article also suggests adding error handling, tests (Mocha, Ava, Jest), debugging utilities, argument parsers (commander or yargs), and other helper modules for a production‑ready generator.
Qunar Tech Salon
Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.