GDI Logo

Intro to Node.js

Welcome!

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

Some "rules"

  • We are here for you!
  • Every question is important
  • Help each other
  • Have fun

Welcome!

Tell us about yourself.

  • Who are you?
  • What do you hope to get out of the class?
  • What is your favorite dinosaur?

The plan

  • What is Node
  • What is npm
  • Use and write an npm module
  • Build a web server

Node.js

  • Server-side JavaScript
  • Event-driven
  • Non-blocking

Server-side?

Clients and servers

How your computer accesses websites

But ALSO how computers talk to each other

JavaScript (in our context) is "client side"

You can run JavaScript on the server with the help of Node.js!

What does non-blocking mean?

(prepare for silly exercise)

When to use Node

  • Scripting on your computer
  • Setting up a web server
  • Building a cross-platform app (ex. Electron)
  • Managing dependencies (npm)
  • Take over the world Maybe?

Let's Develop It!

  • If you haven't yet installed the required materials, install: git and nvm
  • Install version 4.4 of Node with nvm install 4
  • Run node -v in your terminal and see what it says
  • Node comes with npm, but make sure yours is up to date with npm install npm@latest -g
  • Run npm -v in your terminal and see what it says
  • BONUS Create a JavaScript file and run it from the command line using node [YOUR_FILE].js

npm

npm

NPM modules

Some examples

Let's Develop It! (together)

  • Make a new directory and cd into it
  • Run npm init
  • What happens with npm init --yes?

What's a package.json?

package.json is a JSON file that defines information about your app, and npm knows about it

What's a package.json?

There are some rules around names and other parts of your package.json, and npm will warn you if it doesn't like something

What are dependencies?

A dependency is something your application needs to run (it depends on it!).

What are dependencies?

You might install a dependency that relies on something else, adding it to your dependency chain.

Check out the dependency chain for express.

What are dependencies?

Some dependencies are only used in development mode (vs production), and these are known as devDependencies in the package.json file.

How do we use a module?

                      
                    var express = require('express');
                      
                    

Let's Develop It!1

  • Run npm install --save express
  • What happened to your package.json file?
  • Create an app.js file and require express
  • BONUS: Add node_modules/ to your .gitignore file

Express.js

Express features

  • Routes
  • Requests
  • Views

Simple Express Server

                      
    var express = require('express');
    var app = express();

    app.get('/', function (req, res) {
        res.send('Welcome to the GDI Node Workshop!');
    });

    app.listen(3000, function () {
        console.log('Your app is listening on port 3000!');
    });
                        
                    

Run the server from npm

                      
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "node server.js"
    },
                        
                    

npm scripts

npm scripts allow you to use npm to manage a lot of your app using easy commands like npm start, npm test and more.

npm scripts

People use "scripts" in package.json to: compile or preprocess code, run tests, build for a deployment or environment, or really anything!

npm scripts

If you define an arbitrary key (not in npm docs), you can run it using npm run KEY

                      
    "scripts": {
        ...
        "stuff": "echo \"LET'S DO STUFF\""
    }
    ...
    $ npm run stuff
                        
                    

Let's Develop It!2

  • Update app.js to run a simple web server using Express
  • Add a command to package.json to make it easy to run, probably under "start"

HTTP Server Basics: Request/Response

Examples of HTTP requests:

And responses?

They're what you get back from a request 😎

Routes

"Routes" define how a server should respond to a certain request at a certain end point or path.

                        
    // app.<HTTP action>
    app.get('/', function (req, res) {
        res.send('Hello World!');
    });
                        
                    

MVC

  • Model: Data
  • View: UI
  • Controller: Switchboard

Controllers

Our controllers mediate communication between our models and views

Our Home Controller

                        
    exports.index = function (req, res) {
        res.send('Welcome to the GDI Node Workshop!');
    }
                        
                    

Our controller is a Node module!

Node Modules

Node modules do something and expose things to the outside world with exports

Our Home Controller

                        
    exports.index = function (req, res) {
        res.send('Welcome to the GDI Node Workshop!');
    }
                        
                    

How do we use a module?

                      
    var express = require('express');
    // var nameWeUseInOurApp = require('someModule');
                      
                    

How our app integrates with our controller

                        
    // Tell app.js about the home controller using require
    var homeController = require('./controllers/home');

    // Routes
    app.get('/', homeController.index);
                        
                    

Let's Develop It!3

  • Create a new home.js file in a controllers folder.
  • Move your root route to home.js
  • Update app.js to use your controller.
  • BONUS: Add a /* route as a catch-all displays a 404 message.
  • BONUS: Create a new route in your home controller for /about

Templates

Pass data through to your view

Tell our controller about templates

                        
    var path = require('path');

    exports.index = function (req, res) {
        res.sendFile(path.join(__dirname, '../public', 'templates', 'index.html'));
    }
                        
                    

What about CSS? And images?

We need to tell Express which files we allow the user to access

Add static files to our app

                        
    // Serve static files (i.e. images, scripts, styles, templates) from public/ directory
    app.use(express.static('public'));
                        
                    

Let's Develop It!4

  • Update your home controller to load a template, index.html
  • Create a new route in your home controller for /about if you haven't yet
  • Associate /about with a new template
  • Add static assets capability to your app
  • BONUS: Add a CSS file and style your page!

Jade/Pug View Engine

Because writing HTML can be a lot! And view engines are great!

Check out Pug (formerly known as Jade)'s site for examples and an interactive playground

                        
    // template.pug
    h1 Welcome
    a(href="somewhere.com") Some cool link!
                        
                    

Pug

Install & Use Pug

                        
    npm install --save pug
    // in app.js
    app.set('view engine', 'pug');
                        
                    

Pug

Use res.render to use your view engine

                        
    exports.about = function (req, res) {
      res.render('about');
    }
                       
                    

How'd it get the file?

Since we put our about.pug file in views/ Express knows where that is and assumes that's what we mean when we say render

One more thing! Develop faster!

npm install --save-dev nodemon and update your package.json to use nodemon to run app.js. It will live reload so you don't have to start/stop your server!

Let's Develop It!5

  • Install Pug
  • Add some .pug views to a views folder
  • Update your routes to use res.render

APIs!

Application Programming Interface

AKA computers talk to each other

APIs

APIs allow us to request data from a service

Some APIs you might want to use

We can also build our own!!

Let's Develop It!6

  • Download our "database" of dinosaurs
  • Create an api controller
  • Present all the dinosaurs at /api/all
  • Show a dinosaur based on its index in the dinosaurs array at /api/get/:id where id is the index of the dinosaur
  • Consume your API to create a RDaaS (Random Dinosaur as a Service) page!

What we've learned

  • What is Node
  • What is npm
  • Used an npm module
  • Built a web server
  • Wrote a Node module
  • Wrote an API endpoint

Where do we go from here?

  • Import Node modules (browse npm for some ideas) and do some things!
  • Use a database like MongoDB or a service like Firebase
  • Deploy your app to Heroku!

THE END

Don't forget to take the end-of-class survey!

https://tinyurl.com/gdinode

Exercise solutions at https://github.com/pselle/Intro-to-Node.js-Exercises