1) Hallo gebruiker (CLI-args)

  • Naam als command line argument.
  • Print: Hallo, [naam]!
  • Foutmelding als geen naam meegegeven.
Oplossing
// hallo.js
const naam = process.argv[2];
if (!naam) {
  console.error("Gebruik: node hallo.js <naam>");
  process.exit(1);
}
console.log(`Hallo, ${naam}!`);





2) Optelsom (CLI-args)

  • Lees twee getallen via CLI.
  • Toon som, verschil, product, quotiënt.
  • Valideer invoer.
Oplossing
 const [,, input1, input2] = process.argv
 
let getal1 = Number(input1)
let getal2 = Number(input2)
if(Number.isNaN(getal1) || Number.isNaN(getal2)){
    console.error("geef een nummer in")
    process.exit(1)
}
console.log(getal1 + getal2)
console.log(getal1 - getal2)
console.log(getal1 / getal2)
console.log(getal1 * getal2)






3) Rekenmachine (readline)

  • Vraag getal1, getal2, operatie (+ - * / %).
  • Gebruik readline.

const [,, input1, input2, input3] = process.argv

let getal1 = Number(input1)
let getal2 = Number(input2)
let operatie = input3

if(Number.isNaN(getal1) || Number.isNaN(getal2)){
    console.error("geef een getal in")
    process.exit(1)
}
if(!["+", "-", "*", "/"].includes(operatie)){
    console.error("geef een geldige operatie mee: + - * /")
    process.exit(1)
}

switch(operatie){
    case "+":
        console.log(getal1 + getal2)
        break
    case "-":
        console.log(getal1 - getal2)
        break
    case "*":
        console.log(getal1 * getal2)
        break
    case "/":
        console.log(getal1 / getal2)
        break
}

4) Palindroom-checker (CLI-arg)

  • Lees woord via CLI.
Oplossing
const [,,woord] = process.argv
let isPalindroom = true
for(let i = 0; i < woord.length /2; i ++){
    if(woord[i] !== woord[woord.length - 1 - i]){
        isPalindroom = false
    }
}
if(isPalindroom){
    console.log("het is een palindroom")
}else{
    console.log("het is geen palindroom")
}





5) Getallenraden (readline + loops)

  • Random getal 1–20, gebruiker raadt.
  • Hints: te hoog/laag, tel pogingen.

      import readline from "readline";

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
const randomGetal = Math.ceil(Math.random() * 20)
const vraag = (input) => {
    let getal = Number(input)
  if(getal === randomGetal){
    console.log("correct")
    rl.close()
  }else{
    if(getal < randomGetal){
        console.log("te klein")
    }else{
        console.log("te hoog")
    }
    rl.question("geef een getal in: ", vraag);
  }
}

rl.question("geef een getal in: ", vraag);