Introduction to Nomnom
Nomnom is a versatile API library designed to simplify command-line interface (CLI) application development. It offers a range of tools and functionalities to handle inputs, parse arguments, and manage configurations effectively.
Getting Started with Nomnom
const nomnom = require("nomnom");
const opts = nomnom
.option("file", {
abbr: "f",
help: "File to process"
})
.option("verbose", {
abbr: "v",
flag: true,
help: "Print verbose output"
})
.parse();
Detailed API Examples
Adding Options
const nomnom = require("nomnom");
const opts = nomnom
.option("config", {
abbr: "c",
help: "Path to configuration file",
required: true
})
.option("timeout", {
abbr: "t",
help: "Request timeout in milliseconds",
default: 5000
})
.parse();
Working with Commands
const nomnom = require("nomnom");
nomnom.command("start")
.option("port", {
abbr: "p",
help: "Port number",
default: 8000
})
.option("host", {
abbr: "H",
help: "Host name",
default: "localhost"
})
.callback(function (options) {
console.log("Starting server on " + options.host + ":" + options.port);
});
nomnom.command("stop")
.callback(function (options) {
console.log("Stopping server...");
});
nomnom.parse();
Parsers and Validators
const nomnom = require("nomnom");
const opts = nomnom
.option("number", {
abbr: "n",
help: "A number value",
default: 42,
callback: function (val) {
if (isNaN(parseInt(val, 10))) {
return "number must be an integer";
}
return true;
}
})
.option("verbose", {
abbr: "v",
flag: true,
help: "Verbose mode"
})
.parse();
Building an Example Application
Let’s build a simple file processor using nomnom to parse and validate command-line arguments.
// fileProcessor.js
const nomnom = require("nomnom");
const fs = require("fs");
const opts = nomnom
.option("input", {
abbr: "i",
help: "Input file path",
required: true
})
.option("output", {
abbr: "o",
help: "Output file path",
required: true
})
.option("uppercase", {
abbr: "u",
flag: true,
help: "Convert content to uppercase"
})
.parse();
fs.readFile(opts.input, "utf8", (err, data) => {
if (err) {
console.error("Error reading file:", err);
process.exit(1);
}
let content = opts.uppercase ? data.toUpperCase() : data;
fs.writeFile(opts.output, content, (err) => {
if (err) {
console.error("Error writing file:", err);
process.exit(1);
}
console.log("File processed successfully.");
});
});
By following this guide and leveraging the powerful features of nomnom, you can effortlessly develop robust and user-friendly command-line applications.
Hash: cf6b5141d988615963041943df238a6d13e218316f7da3de9715f7a1d51a7bb9