Javascript Command Line Arguments for Kids

Javascript Command Line Arguments for Kids

2024-04-16

Let's focus on teaching how to handle command line arguments in a Node.js script, which are the inputs passed directly to the program when it’s run from the terminal.

JavaScript Lesson: Handling Command Line Arguments with Node.js

Objective: Learn how to use command line arguments in a Node.js script.

Duration: 30 minutes

Part 1: Understanding Command Line Arguments

Concept: Command line arguments are the values passed to the script when it is executed from the terminal.

  1. Explanation:

    • When a Node.js script is run, any words typed after the script name in the command are considered arguments.
    • These arguments can be accessed using process.argv, an array in Node.js.
  2. Example:

    • Open app.js and type the following:
    // Print process.argv
    console.log(process.argv);
    
  3. Run the Script:

    • In the terminal, run the script with additional arguments, e.g., node app.js hello world.
    • Explain how process.argv[0] is the path to Node, process.argv[1] is the path to the script, and process.argv[2], process.argv[3], etc., are the arguments passed.

Part 2: Using Command Line Arguments

Concept: Use command line arguments to change the behavior of the program.

  1. Example:

    • Modify app.js to use arguments in a meaningful way:
    let args = process.argv.slice(2); // Remove the first two elements
    
    if (args.length > 0) {
        console.log(`Hello, ${args[0]}!`);
    } else {
        console.log("Hello, what is your name?");
    }
    
  2. Activity:

    • Run the script with different names to see how it responds, e.g., node app.js Alice.

Part 3: Creating a Simple Application

Concept: Build a small application that uses arguments to perform tasks.

  1. Project Setup:

    • Write a script that checks the first argument to decide what to do:
    const args = process.argv.slice(2);
    
    switch (args[0]) {
        case 'greet':
            console.log(`Hello, ${args[1] || 'stranger'}!`);
            break;
        case 'add':
            const sum = parseInt(args[1], 10) + parseInt(args[2], 10);
            console.log(`The sum is: ${sum}`);
            break;
        default:
            console.log("Unknown command. Please use 'greet' or 'add'.");
    }
    
  2. Activity:

    • Ask them to add another case to perform a different calculation or command, like multiplying numbers or saying goodbye.

Closing

Review the lesson by discussing how command line arguments can make programs more flexible and allow for dynamic input without the need for user interaction during execution. Encourage them to come up with their own ideas for using command line arguments in programs.

This lesson should provide a good understanding of how to handle command line arguments in Node.js, empowering them to start creating more versatile scripts!