Command-Line Application Examples in Node.js

Explore practical examples of creating command-line applications with Node.js, perfect for beginners and enthusiasts.
By Taylor

Introduction

Creating a command-line application with Node.js can be a fun and rewarding way to enhance your programming skills. These applications can automate tasks, interact with users, or serve various purposes. In this article, we will explore three diverse examples to help you understand how to create a command-line application using Node.js.

1. Simple To-Do List App

Context/Use Case

This example demonstrates how to create a simple to-do list application that allows users to add, view, and remove tasks from the command line. It’s a great way to learn about user input and file handling.

const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const filePath = 'tasks.json';

function loadTasks() {
  if (fs.existsSync(filePath)) {
    return JSON.parse(fs.readFileSync(filePath));
  }
  return [];
}

function saveTasks(tasks) {
  fs.writeFileSync(filePath, JSON.stringify(tasks, null, 2));
}

function addTask(task) {
  const tasks = loadTasks();
  tasks.push(task);
  saveTasks(tasks);
  console.log(`Task added: ${task}`);
}

function viewTasks() {
  const tasks = loadTasks();
  console.log('Your Tasks:');
  tasks.forEach((task, index) => {
    console.log(`${index + 1}: ${task}`);
  });
}

function removeTask(index) {
  const tasks = loadTasks();
  if (index > 0 && index <= tasks.length) {
    const removed = tasks.splice(index - 1, 1);
    saveTasks(tasks);
    console.log(`Task removed: ${removed}`);
  } else {
    console.log('Invalid task index.');
  }
}

rl.question('Do you want to add, view or remove a task? (add/view/remove): ', (action) => {
  if (action === 'add') {
    rl.question('Enter task: ', (task) => {
      addTask(task);
      rl.close();
    });
  } else if (action === 'view') {
    viewTasks();
    rl.close();
  } else if (action === 'remove') {
    rl.question('Enter task index to remove: ', (index) => {
      removeTask(parseInt(index));
      rl.close();
    });
  } else {
    console.log('Unknown action.');
    rl.close();
  }
});

Notes/Variations

  • You can expand this application by adding features like marking tasks as completed or prioritizing tasks.
  • Consider adding error handling for invalid JSON or file issues.

2. Weather Fetching App

Context/Use Case

This example shows how to create a command-line application that fetches weather information for a specified city using an external API. It’s perfect for learning how to make API requests.

const axios = require('axios');
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const apiKey = 'YOUR_API_KEY'; // Replace with your API key

function fetchWeather(city) {
  axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`)
    .then(response => {
      const weather = response.data;
      console.log(`Current temperature in ${city}: ${weather.main.temp}°C`);
    })
    .catch(error => {
      console.error('Error fetching weather data:', error.message);
    });
}

rl.question('Enter city name: ', (city) => {
  fetchWeather(city);
  rl.close();
});

Notes/Variations

  • You can enhance this app by adding more weather details such as humidity, pressure, etc.
  • Explore using environment variables to securely store your API key.

3. URL Shortener

Context/Use Case

This example illustrates how to create a basic URL shortener that stores shortened URLs in memory. It’s a practical way to learn about data storage and user interaction.

const readline = require('readline');
const validUrl = require('valid-url');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const urlDatabase = {};
let id = 1;

function shortenUrl(longUrl) {
  const shortUrl = `short.ly/${id}`;
  urlDatabase[shortUrl] = longUrl;
  id++;
  console.log(`Shortened URL: ${shortUrl}`);
}

function getLongUrl(shortUrl) {
  if (urlDatabase[shortUrl]) {
    console.log(`Long URL: ${urlDatabase[shortUrl]}`);
  } else {
    console.log('URL not found.');
  }
}

rl.question('Do you want to shorten a URL or retrieve one? (shorten/retrieve): ', (action) => {
  if (action === 'shorten') {
    rl.question('Enter the long URL: ', (longUrl) => {
      if (validUrl.isUri(longUrl)) {
        shortenUrl(longUrl);
      } else {
        console.log('Invalid URL.');
      }
      rl.close();
    });
  } else if (action === 'retrieve') {
    rl.question('Enter the shortened URL: ', (shortUrl) => {
      getLongUrl(shortUrl);
      rl.close();
    });
  } else {
    console.log('Unknown action.');
    rl.close();
  }
});

Notes/Variations

  • Consider using a database like MongoDB or SQLite for persistent storage.
  • Implement additional features like deleting URLs or viewing all shortened URLs.

These examples of creating a command-line application with Node.js showcase various functionalities from simple tasks to more interactive applications. By building these projects, you can gain hands-on experience and confidence in your Node.js skills!