Reading Lines of Input
So far, your programs print the same thing every time they run. Most real programs work with input, which is data that comes from outside the program. In a browser, input comes from forms and clicks. In Node.js, input can come as text on standard input, and that is how the exercises in this course give your program its data.
This line reads all of the input and splits it into lines:
const lines = require("fs").readFileSync(0, "utf8").split("\n");
For now, copy this line as it is. Every part of it will make sense later in the course. In short:
require("fs")loads Node's file tools.readFileSync(0, "utf8")reads all of standard input as one string. The0means standard input..split("\n")cuts that string at each line break (\n), so you get the lines one by one.
After this line, lines[0] is the first line of input, lines[1] is the second line, and so on. The numbers start at 0, not 1.
Here is a full program. Its input is these two lines:
Ada
30
<!-- stdin: Ada\n30 -->
const lines = require("fs").readFileSync(0, "utf8").split("\n");
const name = lines[0];
const age = Number(lines[1]);
console.log(`Hello, ${name}!`);
console.log(`Next year you'll be ${age + 1}`);
Output:
Hello, Ada!
Next year you'll be 31
Every line of input is a string. Even when the line is 30, your program gets the text "30", not the number 30. Number(...) turns the text into a real number, so age + 1 gives 31. Without Number, age + 1 would join the text "30" and the 1 instead of adding them. You will see this mistake for yourself in the next lesson.
Each exercise has test cases. Every test case gives your program its own input lines and checks what it prints. Some test cases are hidden and use different input. So your program must work with the input it gets, not only with the example in the comment.
In the exercise, read a name and an age, and convert the age with Number.