Command Line Interfaces (CLIs) can be powerful tools for automation, user interaction, and improving productivity. In this tutorial, we’ll build a simple CLI using Node.js with the help of chalk
for styling, fs-extra
for file operations, and inquirer
for user input.
What Are Chalk, fs-extra, and Inquirer?
Chalk
Chalk is a popular library used for styling and coloring terminal output in Node.js. It allows you to easily add colors, background colors, and styles like bold or underline to text displayed in the terminal.
Example usage:
import chalk from 'chalk';
console.log(chalk.green('Success!'));
console.log(chalk.red.bold('Error!'));
fs-extra
fs-extra is an extension of Node.js's built-in fs
module, providing additional methods for handling file system operations. It includes functions like outputFile
, copy
, and remove
, which simplify working with files and directories.
Example usage:
import fs from 'fs-extra';
fs.outputFileSync('example.txt', 'Hello, World!');
console.log('File created successfully.');
Inquirer
Inquirer is a library for handling interactive user prompts in the terminal. It allows you to create command-line questionnaires, take user input, and handle multiple types of prompts.
Example usage:
import inquirer from 'inquirer';
inquirer.prompt([
{
type: 'input',
name: 'username',
message: 'What is your name?'
}
]).then(answers => {
console.log(`Hello, ${answers.username}!`);
});
Prerequisites
Before we begin, ensure you have the following installed:
- Node.js (v14 or later)
- npm (Node Package Manager)
Step 1: Initialize a Node.js Project
Create a new directory for your CLI and initialize a new Node.js project:
mkdir my-cli-tool && cd my-cli-tool
npm init -y
This will generate a package.json
file.
Step 2: Install Required Dependencies
We need to install the following npm packages:
chalk
: For styling terminal outputfs-extra
: Provides additional file system methodsinquirer
: Handles user prompts and inputs
Run the following command to install them:
npm install chalk fs-extra inquirer
Step 3: Create the CLI Script
Inside your project folder, create a file named index.js
and add the following code:
#!/usr/bin/env node
import chalk from 'chalk';
import fs from 'fs-extra';
import inquirer from 'inquirer';
console.log(chalk.blue('Welcome to My CLI Tool!'));
async function main() {
const answers = await inquirer.prompt([
{
type: 'input',
name: 'filename',
message: 'Enter the name of the file to create:'
},
{
type: 'input',
name: 'content',
message: 'Enter the content for the file:'
}
]);
const { filename, content } = answers;
const filePath = `./${filename}`;
try {
await fs.outputFile(filePath, content);
console.log(chalk.green(`File "${filename}" created successfully!`));
} catch (error) {
console.log(chalk.red('Error creating file:', error));
}
}
main();
Step 4: Make the Script Executable
Modify package.json
to add a bin
field:
"bin": {
"mycli": "index.js"
}
Also, modify the script to use ES module support by adding this to package.json
:
"type": "module"
Now, make the script executable:
chmod +x index.js
Step 5: Link the CLI Globally
To use the CLI as a global command, run:
npm link
This allows you to run the CLI tool with:
mycli
Step 6: Test the CLI
Try running your CLI tool:
mycli
It will prompt you to enter a filename and content, then create a file with the given details.
Conclusion
You’ve now built a simple Node.js CLI tool using chalk
for styling, fs-extra
for file handling, and inquirer
for user input. You can extend this by adding more commands, handling errors better, and improving the user experience.