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.
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();
}
});
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();
});
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();
}
});
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!