Input and Output

Terminal I/O

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

node load code, decoded

process.stdin.on('data', (chunk) => { console.log(chunk) })
phrase meaning
process.stdin hey terminal input,
.on('data', ... ) when you get some data,
(chunk) please name it chunk
=> and send it to
{ ... } this block of code
console.log(chunk) print chunk to the terminal

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.on('data', (chunk) => {
        let name = chunk.toString(); 
        console.log("Hello, " + name + "!"); 
  3. Save the file and switch back to the terminal

  4. Run the program using node hello.js

  5. Type in your name and press the RETURN (or ENTER) key

What happens? Is this what you expected?



Let's fix this

The newline character

Trim it

LAB: fixing Hello, Friend

LAB: Capitalization

Hint: remember slice ?

LAB: Crazy Name

Evented I/O: A Gentle Introduction

This is a very big topic, but briefly...


Traditional programs are written using sequences, which are performed in order like a traditional recipe, performed by a single chef:

  1. preheat oven to 350°
  2. roll out dough on baking sheet
  3. cut out cookies and remove excess dough
  4. put baking sheet in the oven
  5. wait 20 minutes and remove baking sheet from oven
  6. place cookies on a tray and wait 10 more minutes for cookies to cool
  7. decorate the cookies with icing and sprinkles

Sequences in Parallel

Even though the recipe is written in a strict order, many of these steps can happen simultaneously or in parallel.

For instance, you don't have to wait for the oven to be preheated before rolling out the dough.

Or, you could have one cook rolling, cutting, and baking, and another cook removing and decorating.


NodeJS programs are written using events, which is like a bunch of cooks, each performing one part of the recipe.

Evented programs are often more flexible and high-performance than traditional sequenced programs, but they can be more confusing for humans to write and to read (and to debug!).

Also, sequences naturally end when they are finished, but evented programs will just keep doing the same things over and over again, as long as the triggers keep happening.

On vs Once

If you have a simple sequence in mind, and want to emulate it using an evented system, you could use the following technique:

Set up your event responders to happen only once.

In NodeJS, this is accomplished by sending the once message in place of the on message.

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

LAB: Full Name


You just wrote a program!

You are now officially a coder. HIGH FIVE!

Lab: Name Length

>> Logic >> << Loops <<



Input And Output Slides - Code Like This