How to make a basic website with Node, Express, and Pug

  1. Create a new folder, and go into it.
    mkdir simple-website && cd simple-website
    
  2. Initialize a new Node project within the folder.
    npm init
    
  3. Fill out the info it asks you for. In most cases, the defaults will be fine. This will create a package.json file in the folder.

  4. We are going to install a package called Express. It lets us get websites up and running quickly and easily. We are also going to install Morgan, a logger for Express.

    npm install --save express morgan
    
  5. Additionally, we are going to install Pug, an HTML template language.
    npm install --save pug
    
  6. Install nodemon, a program that watches your Node application during development, and restarts the server any time there are changes.
    npm install -g nodemon
    
  7. In your package.json, replace the contents of "scripts" with these commands.
    {
        "watch": "nodemon server.js -e js,pug", // runs nodemon to watch for server updates
        "start": "node server.js" // runs the server without nodemon
    }
    
  8. Make a new file called server.js, and paste in the following code:
    // require all dependencies
    var express = require('express');
    var logger = require('morgan');
    var app = express();
    
    // add logging and static middleware to express
    app.use(logger('dev'));
    
    // set up the template engine
    app.set('views', './views');
    app.set('view engine', 'pug');
    
    // GET response for '/'
    app.get('/', function (req, res, next) {
    
        try {
    
            // render the 'index' template, and pass in a few variables
            res.render('index', { title: 'Hey', message: 'Hello there!' });
    
        } catch (e) { // if there are any errors, send them off the the logger
            next(e);
        }
    
    });
    
    // start up the server
    app.listen(process.env.PORT || 3000, function () {
        console.log('Listening on http://localhost:' + (process.env.PORT || 3000));
    });
    
  9. Make a new folder called views, and within it make a new file called **index.pug*. In that file, paste the following code:
    html
        head
            title= title
        body
            h1= message
    

This is essentially equal to writing:

```
<html>
    <head>
        <title>title</title>
    </head>
    <body>
        <h1>message</h1>
    </body>
</html>
```

But as you can see, the Pug version is much shorter and easier to read (plus, we can easily pass in variables).

  1. Start up your server with
    npm run watch
    
  2. In your browser, go to http://localhost:3000 to view your site. Try making changes to server.js and reloading the webpage to see it change.