Automating Real-Life Tasks
Alright, let’s kick off Automating Real-Life Tasks. This is where the fun really begins—building CLI tools that can save you tons of time by automating tedious tasks.
We’ve covered the basics, and now we’re going to level up your CLI game. In this section, we’ll build tools that make your life easier by automating tasks you probably hate doing manually, like organizing files, scraping websites for data, or even renaming files in bulk. Get ready to supercharge your workflow!
2.1 Automating File Management
Ever stared at a folder full of random files—images, PDFs, documents—and wished they could just organize themselves? Well, now they can! We’re going to build a CLI tool that organizes files into different folders based on their file type.
Step 1: Setting Up the Tool
Let’s start by creating a new tool to handle file organization. Inside your project folder, create a new file called organize.js
:
touch organize.js
In organize.js
, we’ll start by using Node.js’s built-in fs
module to handle files and folders. Here’s how to get started:
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const folderPath = process.argv[2] || '.';
const organizeFiles = () => {
fs.readdir(folderPath, (err, files) => {
if (err) {
console.log("Error reading the directory");
return;
}
files.forEach(file => {
const ext = path.extname(file).toLowerCase();
if (!ext) return; // Skip files with no extension (e.g., folders)
let folderName = ext.slice(1); // Remove the dot from the extension
let folder = path.join(folderPath, folderName);
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder);
}
fs.renameSync(path.join(folderPath, file), path.join(folder, file));
});
console.log("Files organized successfully!");
});
};
organizeFiles();
Step 2: How It Works
fs.readdir
: Reads all files in the given folder.path.extname
: Extracts the file extension (like.jpg
or.pdf
).fs.mkdirSync
: Creates a new folder if it doesn’t already exist.fs.renameSync
: Moves the file into the corresponding folder.
Step 3: Run the Tool
To use this tool, run it like this:
node organize.js /path/to/your/folder
It will create folders for each file type (like jpg
, pdf
, etc.) and move the files into their respective folders. Magic, right? 🎩✨
2.2 Web Scraping with CLI Tools
Want to extract data from a website but don’t want to manually copy-paste stuff all day? Let’s build a simple web scraper to grab the latest news headlines from a site.
Step 1: Install Axios and Cheerio
We’ll need two libraries:
- Axios: To make HTTP requests.
- Cheerio: To parse the HTML and select elements, kind of like jQuery but for Node.js.
Run this to install both:
npm install axios cheerio
Step 2: Building the Scraper
Let’s scrape the front page of a news site like Hacker News to grab the latest headlines. In your project folder, create a file called scrape.js
:
touch scrape.js
Now, let’s write the code to scrape the headlines:
#!/usr/bin/env node
const axios = require('axios');
const cheerio = require('cheerio');
const scrapeNews = async () => {
try {
const { data } = await axios.get('https://news.ycombinator.com/');
const $ = cheerio.load(data);
$('a.storylink').each((i, element) => {
const title = $(element).text();
console.log(`${i + 1}: ${title}`);
});
} catch (error) {
console.log("Error fetching the data", error);
}
};
scrapeNews();
Step 3: Running the Scraper
To run the scraper, use the command:
node scrape.js
This will print out the latest headlines like this:
1: Startup raises $100M for AI-powered coffee machines
2: Why Rust is the future of systems programming
3: New breakthroughs in quantum computing
You’ve just built a simple news scraper that grabs real-time data from the web. No more manually visiting websites!
2.3 Task Automation: Bulk File Renamer
Ever needed to rename a bunch of files but didn’t want to click through them one by one? Let’s build a CLI tool to rename all files in a folder at once based on a pattern you choose. This is perfect for organizing photos, documents, or anything else.
Step 1: Create the Renamer Script
In your project folder, create a file called rename.js
:
touch rename.js
Here’s the code for the renamer:
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const folderPath = process.argv[2] || '.';
const newFileName = process.argv[3] || 'file';
const renameFiles = () => {
fs.readdir(folderPath, (err, files) => {
if (err) {
console.log("Error reading the directory");
return;
}
files.forEach((file, index) => {
const ext = path.extname(file);
const oldPath = path.join(folderPath, file);
const newPath = path.join(folderPath, `${newFileName}-${index + 1}${ext}`);
fs.renameSync(oldPath, newPath);
});
console.log("Files renamed successfully!");
});
};
renameFiles();
Step 2: How It Works
fs.readdir
: Reads all files in the folder.fs.renameSync
: Renames each file with the pattern you specify (newFileName-1.ext
,newFileName-2.ext
, etc.).
Step 3: Running the Tool
To run the renamer, use the command:
node rename.js /path/to/folder new-name
For example, if you run:
node rename.js ./images vacation-photo
Your files will be renamed to:
vacation-photo-1.jpg
vacation-photo-2.jpg
vacation-photo-3.jpg
...
Just like that, you’ve saved yourself hours of manually renaming files!
Wrapping Up Tutorial 2
In this part, we’ve built three powerful automation tools:
- A file organizer to sort files by type,
- A web scraper to grab headlines from a website,
- And a bulk file renamer to give your files consistent, meaningful names.
These are practical examples that you can tweak to fit your own workflows. And we’re just getting started. In the next section, we’ll take these tools and make them even more polished and professional, so stay tuned!