ProductPromotion
Logo

0x3d.Site

is designed for aggregating information.

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!

Creating CLI Tools with Node.js

Learn how to create powerful, professional-grade command-line tools with Node.js in this comprehensive course. From setting up your environment and automating real-life tasks to distributing your tool and adding advanced features like async tasks, multiple commands, configuration files, and API integrations, this guide covers it all. Perfect for developers looking to simplify workflows and build scalable tools, this course offers clear, practical steps with a focus on usability and real-world applications.

Questions & Answers

to widen your perspective.

Tools

available to use.

Providers

to have an visit.

Resouces

to browse on more.
0x3d
https://www.0x3d.site/
0x3d is designed for aggregating information.
NodeJS
https://nodejs.0x3d.site/
NodeJS Online Directory
Cross Platform
https://cross-platform.0x3d.site/
Cross Platform Online Directory
Open Source
https://open-source.0x3d.site/
Open Source Online Directory
Analytics
https://analytics.0x3d.site/
Analytics Online Directory
JavaScript
https://javascript.0x3d.site/
JavaScript Online Directory
GoLang
https://golang.0x3d.site/
GoLang Online Directory
Python
https://python.0x3d.site/
Python Online Directory
Swift
https://swift.0x3d.site/
Swift Online Directory
Rust
https://rust.0x3d.site/
Rust Online Directory
Scala
https://scala.0x3d.site/
Scala Online Directory
Ruby
https://ruby.0x3d.site/
Ruby Online Directory
Clojure
https://clojure.0x3d.site/
Clojure Online Directory
Elixir
https://elixir.0x3d.site/
Elixir Online Directory
Elm
https://elm.0x3d.site/
Elm Online Directory
Lua
https://lua.0x3d.site/
Lua Online Directory
C Programming
https://c-programming.0x3d.site/
C Programming Online Directory
C++ Programming
https://cpp-programming.0x3d.site/
C++ Programming Online Directory
R Programming
https://r-programming.0x3d.site/
R Programming Online Directory
Perl
https://perl.0x3d.site/
Perl Online Directory
Java
https://java.0x3d.site/
Java Online Directory
Kotlin
https://kotlin.0x3d.site/
Kotlin Online Directory
PHP
https://php.0x3d.site/
PHP Online Directory
React JS
https://react.0x3d.site/
React JS Online Directory
Angular
https://angular.0x3d.site/
Angular JS Online Directory