Les 2 — Node.js: Bestanden

Interactieve programma's schrijven met Node.js

Gebruikersinvoer

Met Node.js kun je de gebruiker iets laten typen in de terminal via de readline module.

import readline from "readline";

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const begroet = (klas) => {
  console.log(klas);
}

rl.question("Wat is je naam? ", begroet);

Gebruikersinvoer

Functies zijn variabelen

function sayHello(naam){
  console.log(naam)
} # oude syntax

const sayHello = (naam) =>{
  console.log(naam)
} # nieuwe syntax

Gebruikersinvoer

Functies mee geven als variabele


const sayHello = () =>{
  console.log("Hello")
}
const execute3Times = (callableParam) =>{
  callableParam()
  callableParam()
  callableParam()
}
execute3Times(sayHello)

Gebruikersinvoer

Functies mee geven als variabele


const sayHello = (naam) =>{
  console.log("Hello "+naam)
}
const execute3Times = (callableParam, param1) =>{
  callableParam(param1)
  callableParam(param1)
  callableParam(param1)
}
execute3Times(sayHello, param1)

Gebruikersinvoer

Wrapper functies mee geven als variabele


const sayHello = (naam) =>{
  console.log("Hello "+naam)
}
const execute3Times = (callableParam) =>{
  callableParam()
  callableParam()
  callableParam()
}

const sayHelloAnton = () =>{
  sayHello("Anton")
}
execute3Times(sayHelloAnton)

Gebruikersinvoer

Variabele substitutie


const appels = 3
console.log(appels)
// ----------------------
console.log(3)

Gebruikersinvoer

Variabele substitutie


const sayHelloAnton = () =>{
  sayHello("Anton")
}
execute3Times(sayHelloAnton)
// ----------------------
execute3Times(()=>{sayHello("Anton")})

Gebruikersinvoer

Callback functies laten toe om Non blocking te werken, de code moet niet volledig wachten omdat de user iets moet doen. Later gaan we zien hoe je callback functies kan vervangen met async/await

import readline from "readline";
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
const begroet = (klas) => {
  console.log(klas);
}
rl.question("Wat is je naam? ", begroet);
console.log("test")

Oefening 1 — Vraag de leeftijd

  1. Vraag de gebruiker naar hun naam.
  2. Vraag daarna de leeftijd.
  3. Log een zin zoals: Hey Sara, je bent 20 jaar oud!