In JavaScript,
console.log
means "print a line to the terminal"In NodeJS,
process.stdin
means "input coming from the terminal"process.stdin.once('data', (chunk) => { console.log(chunk.toString()) } )
The weirdness is explained on the next slide!
process.stdin.once('data',
(chunk) => { console.log(chunk.toString()) }
)
once
is a function that takes two parameters, and its second parameter is another function
phrase | meaning |
---|---|
process.stdin |
hey terminal input, |
.once('data', ... )
|
when you get some data, |
(chunk) |
please name it chunk
|
=> |
and send it to |
{ ... }
|
this block of code |
console.log(chunk.toString()) |
convert it to a string and print it to the terminal |
The previous one-liner code is equivalent to this:
function printLine(chunk) {
console.log(chunk)
}
process.stdin.once('data', printLine);
The printLine
function itself is called a callback
(since you are asking the I/O device to call you back when it receives input).
hello.js
in your text editorconsole.log("What is your name?");
process.stdin.once('data', (chunk) => {
let name = chunk.toString();
console.log("Hello, " + name + "!");
});
node hello.js
What happens? Is this what you expected?
Uh-oh! We've got trouble... what is that exclamation point doing way down there?
The first thing to do is DON'T PANIC!
You are totally going to figure this out.
And even if you don't, you haven't actually broken anything.
In fact, it's really hard to break a computer just by typing, so stay calm.
trim
to a string, it will remove all SPACES and NEWLINES from both endsconsole.log("What is your name?");
process.stdin.once('data', (chunk) => {
let name = chunk.toString().trim();
console.log("Hello, " + name + "!");
});
console.log("What is your name?");
process.stdin.once('data', (chunk) => {
let name = chunk.toString().trim();
console.log("Hello, " + name + "!");
process.exit();
});
Note that:
process.exit
uses the same process
object as process.stdin
process.exit()
must be inside the callback
hello.js
program should currently look something like this:console.log("What is your name?");
process.stdin.on('data', (chunk) => {
let name = chunk.toString();
console.log("Hello, " + name + "!");
});
hello.js
so that it doesn't always say hello!
hello.js
so it keeps asking for names forever...
hello.js
so that it says "Go away!" if the user's name is any one of a number of evil namesVolDeMort
/