Skip to main content

Chapter 12 - Designing and Deploying Command Line Programs (JavaScript)

Here's a JavaScript-flavoured version of the same concepts, with small JS/Node examples for each idea.


Designing and Deploying Command Line Programs (intro)

Goal: move from running code in a browser console to running scripts as real commands from the terminal, using Node.js, npm, and deployment techniques.


A Program by Any Other Name

Same terms apply: program, script, command, shell script/batch file, application, app, web app. In JS-land, you'll typically run .js files with node.

Example shell script:

#!/usr/bin/env bash
echo "Starting backup..."
node backup_to_zip.js
echo "Done."

Using the Terminal

Same CLI/terminal/shell/console concepts apply. Run JS files with node:

Example (Windows):

C:\Users\al> node C:\Users\al\Scripts\yourScript.js

Example (Linux/macOS):

node yourScript.js

The cd, pwd, dir, and ls Commands

Same shell commands apply regardless of language:

  • cd changes current directory.
  • pwd (macOS/Linux) prints working directory.
  • dir (Windows) and ls (macOS/Linux) list contents.

The PATH Environment Variable

PATH is a "search list" of folders the shell looks in to find commands like node or npm.

  • Windows: checks CWD first, then folders in PATH.
  • macOS/Linux: only PATH; use ./program for CWD.
echo $PATH
# /home/al/.local/bin:/usr/local/bin:/usr/bin:...

PATH Editing

Same approach: create a Scripts folder and add it to PATH.

  • Windows: edit user "Path" via "Edit environment variables for your account".
  • macOS: add export PATH=/Users/al/Scripts:$PATH to ~/.zshrc.
  • Linux: add export PATH=/home/al/Scripts:$PATH to ~/.bashrc.

The which and where Commands

  • which node (macOS/Linux)
  • where node (Windows)
which node
# /usr/local/bin/node

Virtual Environments (Node.js equivalent)

Node.js isolates dependencies per project using node_modules and package.json — each project gets its own dependencies automatically via npm install.

Creating a project

mkdir my-project && cd my-project
npm init -y

Creates package.json — the equivalent of a Python venv's isolated package list.

How isolation works

  • npm install puts packages in the local node_modules/ folder.
  • No activation/deactivation needed — Node resolves from the nearest node_modules automatically.
  • Global installs (npm install -g) go to a system-wide folder; prefer local installs.

Removing a project's dependencies

Delete the node_modules folder; recreate with npm install from package.json.


Installing Packages with npm

Use npm (Node Package Manager) instead of pip.

Installing, Listing, Upgrading, Uninstalling

Install:

npm install package_name

List:

npm list

Upgrade:

npm update package_name

Install specific version:

npm install package_name@1.17.4

Uninstall:

npm uninstall package_name

Global vs local installs

# Local (project only) — preferred
npm install chalk

# Global (available everywhere)
npm install -g nodemon

Self-Aware Node.js Programs

Node.js equivalents for knowing about yourself and environment.

Key pieces:

  • __filename – absolute path to the current .js file.
  • __dirname – directory containing the current file.
  • process.execPath – path to the Node executable.
  • process.version – Node version string.
  • process.platform'win32', 'darwin', 'linux'.
  • os.type()'Windows_NT', 'Darwin', 'Linux'.
  • os.arch() – CPU architecture.

Example:

const os = require("os");
const path = require("path");

console.log(__filename); // script path
console.log(__dirname); // script directory
console.log(process.execPath); // node binary path
console.log(process.version); // e.g. 'v20.11.0'
console.log(process.platform); // 'darwin', 'win32', 'linux'
console.log(os.type()); // 'Darwin', 'Windows_NT', 'Linux'

Checking whether a module is installed:

try {
require("nonexistentModule");
} catch (err) {
console.error("nonexistentModule is required. Please install it.");
process.exit(1);
}

Text-Based Program Design

Same TUI/CLI design principles apply in JavaScript.

Short Command Names

Same advice: use short names (ccwd not copy-current-working-directory); check which/where for collisions.

You can add a "bin" field to package.json to create named commands:

{
"bin": {
"ccwd": "./ccwd.js"
}
}

Command Line Arguments

Use process.argv (similar to sys.argv). The first two entries are node and the script path.

node yourScript.js spam eggs

Inside yourScript.js:

console.log(process.argv);
// ['/usr/local/bin/node', '/path/to/yourScript.js', 'spam', 'eggs']

const args = process.argv.slice(2);
console.log(args); // ['spam', 'eggs']

For complex argument parsing, use packages like commander or yargs.

Clipboard I/O

Use the clipboardy package (equivalent of pyperclip).

npm install clipboardy
import clipboard from "clipboardy";

const text = clipboard.readSync();
const result = text.trim().toUpperCase();
clipboard.writeSync(result);
console.log("Transformed text copied to clipboard.");

Colorful Text with chalk

Use chalk for colored terminal text (equivalent of bext for colors).

npm install chalk
import chalk from "chalk";

console.log(chalk.red("This text is red."));
console.log(chalk.red.bgBlue("Red text on blue background."));
console.log(chalk.green.bold("Bold green text."));

For cursor movement and screen clearing, use ansi-escapes or terminal-kit:

// Clear screen
console.clear();

// Or using process.stdout
process.stdout.write("\x1Bc");

Terminal Clearing

const os = require("os");
const { execSync } = require("child_process");

function clear() {
execSync(os.platform() === "win32" ? "cls" : "clear", { stdio: "inherit" });
}

Or simply:

console.clear();

Sound and Text Notification

Use the play-sound package for audio playback.

npm install play-sound
const player = require("play-sound")();

player.play("hello.mp3", (err) => {
if (err) console.error("Error playing sound:", err);
});

Notes:

  • play-sound is non-blocking by default (uses a callback).
  • For cross-platform desktop notifications, use the node-notifier package.

Overall idea of the chapter

Chapter 12 covers everything needed to turn Node.js scripts into real command-line tools: terminal navigation, PATH setup, npm and node_modules for dependency isolation, self-awareness (__filename, process, os), and TUI design patterns (arguments via process.argv, clipboard with clipboardy, colored text with chalk, sound with play-sound).