DEV Community

Cover image for Learning Node.js in 30 Days with AI - Day 3
King Triton
King Triton

Posted on • Edited on

Learning Node.js in 30 Days with AI - Day 3

On the third day of learning Node.js, I read an article written by ChatGPT and learned about working with the console in Node.js. The article covered two main topics: command line arguments and console output.

What I Learned

  1. Command Line Arguments (process.argv)

    • process.argv is an array that contains the command line arguments passed when the script is launched.
    • The first two elements of the array are the path to Node.js and the path to the script. The remaining elements are the arguments passed during program execution.
    • For example, if you run the command node script.js arg1 arg2, the process.argv array will include the path to Node.js, the path to the script, and the arguments arg1 and arg2.
  2. Console Output (console.log)

    • console.log is used to output information to the console, which is useful for debugging and displaying the results of your program.
    • For example, when you run the code console.log('Hello, World!'), the console will display the message "Hello, World!".

Practical Task

I wrote a program that takes an operation (addition, subtraction, multiplication, division) and two numbers from the command line, performs the specified operation, and outputs the result to the console.

const args = process.argv.slice(2); // Remove the first two elements

const operation = args[0]; // Operation: "add", "subtract", "multiply", "divide"
const num1 = parseFloat(args[1]); // First number
const num2 = parseFloat(args[2]); // Second number

let result;

switch (operation) {
  case 'add':
    result = num1 + num2;
    break;
  case 'subtract':
    result = num1 - num2;
    break;
  case 'multiply':
    result = num1 * num2;
    break;
  case 'divide':
    result = num1 / num2;
    break;
  default:
    console.log('Unknown operation. Use "add", "subtract", "multiply", or "divide".');
    process.exit(1); // Exit the program with an error code
}

console.log(`Result: ${result}`);
Enter fullscreen mode Exit fullscreen mode

My Experience

After running the program with the command node calculator.js multiply 7 3, I received the result Result: 21, which confirmed that my code was correct.

Conclusion

This experience showed me how easy it is to work with the console in Node.js. I learned how to pass command line arguments, use them in a program, and output results to the console. This lesson strengthened my knowledge and provided practical skills that will be useful as I continue learning Node.js.

All lessons created by ChatGPT are published here: https://king-tri-ton.github.io/learn-nodejs/.

Top comments (0)