Terminal I/O

process.stdin.once('data', (chunk) => { console.log(chunk.toString()) } )

The weirdness is explained on the next slide!

node load code, decoded

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

Welcome to Callback City!

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).

LAB: Hello, friend!

  1. Open hello.js in your text editor
  2. Change it to contain the following code:
console.log("What is your name?");
process.stdin.once('data', (chunk) => {
    let name = chunk.toString();
    console.log("Hello, " + name + "!");
});
  1. Save the file and switch back to the terminal
  2. Run the program using node hello.js
  3. Type in your name and press the Return key (also called Enter)

What happens? Is this what you expected?

Yikes!

Control-C to close

Let's fix this

The newline character

Trim it

fixing Hello, Friend

console.log("What is your name?");
process.stdin.once('data', (chunk) => {
    let name = chunk.toString().trim();
    console.log("Hello, " + name + "!");
});

This Way To The Exit

console.log("What is your name?");
process.stdin.once('data', (chunk) => {
    let name = chunk.toString().trim();
    console.log("Hello, " + name + "!");
    process.exit();
});

Note that:

Good Friend, Bad Friend

console.log("What is your name?");
process.stdin.on('data', (chunk) => {
    let name = chunk.toString();
    console.log("Hello, " + name + "!");
});

Infinite Names

Enemies List

 Previous Next 

Outline

[menu]

/