Web Dev With Express

Express is a Node module that helps you build web sites and applications with JavaScript on the back end.

I'm going to guide you through creating a simple express app. If you'd like to follow along make a new directory and create a file called index.js.

Then type npm init and answer the usual questions.

Next, type npm install express --save.

Ok, we're ready to get started. Open up index.js and put this code in there:

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

app.get('/', function (req, res) {  
    res.send('Wazzup?')
})

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

Save, run node ., and go to http://localhost:3000/ to see a warm greeting.

Yeah, that's cool and all, but I know you want a real web page. Hit control-c and let's add a new file to your project.

First, we'll need to make a public folder:

mkdir public  

Now save the following as public/index.html

<!DOCTYPE html>  
<html>  
    <head>
        <title>Greetings</title>
    </head>
    <body>
        <h1>Greetings</h1>
        <p>Hello there.</p>
    </body>
</html>  

And modify index.js like so...

var express = require('express')  
var app = express()  
app.use(express.static('public'))

app.get('/', function (req, res) {  
    res.send('Wazzup?')
})

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

Run this thing again and go to http://localhost:3000/index.html. You've now got a static file server. Put any file in public and you can get to it via localhost:3000/anyfile.whatevs.

Pretty neat huh? If you like, you can have a look at the code for this project (such as it is :) ) here.

Ok, check this out. Get out of that project. Now let's try automating this process with the Express generator.

Install it like so:

npm install express-generator -g  

Next, run

express myapp  

After it's done, cd inside the app and type

npm install  

This might take a bit of time...

If you're on Mac or Linux type:

DEBUG=myapp:* npm start  

Windows users type

set DEBUG=myapp:* & npm start  

And go to http://localhost:3000/ once more. Pretty fancy eh?

There's lots more to Express. Heck, we could probably spend a few posts just talking about what the Express generator made. We'll get to it. :)

Looking for a software developer?