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.
Command Line Arguments (process.argv)
Console Output (console.log)
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}`);
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.
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/.
The above is the detailed content of Learning Node.js in Days with AI - Day 3. For more information, please follow other related articles on the PHP Chinese website!