Free Code Camp and Learning Express.js: Static

Moving on, here’s the next exercise in the FreeCodeCamp Express tutorial, Static.  The directions and hints:

STATIC
 Exercise 2 of 8
Apply static middleware to serve index.html file without any routes.
Your solution must listen on the port number supplied by process.argv[2].
The index.html file is provided and usable via the path supplied by process.argv[3]. However, you can use your own file with this content:
    <html>
      <head>
        <title>expressworks</title>
        <link rel=”stylesheet” type=”text/css” href=”/main.css”/>
      </head>
      <body>
        <p>I am red!</p>
      </body>
    </html>
——————————————————————————-
## HINTS
This is how you can call static middleware:
    app.use(express.static(path.join(__dirname, ‘public’)));
For this exercise expressworks will pass you the path:

    app.use(express.static(process.argv[3]||path.join(__dirname, ‘public’)));

There were a couple sneaky parts to this one.  Let’s begin with the easy stuff.

First, we require express, and we assign process.argv[2] to port and process.argv[3] to filePath.  We also assign express() to app.  We know we’re listening on a port, so we add app.listen(port).  And here is what we have so far:

var express = require('express');
var port = process.argv[2];
var filePath = process.argv[3];

var app = express();

/* do stuff here */

app.listen(port);

Our application is going to go between the last two lines where it says /* do stuff here */.  At first, I thought we needed the framework from the previous lesson:

app.get('/home', function(req, res) {

})

And I added the command for the static middleware in there:

app.get('/home', function(req, res) {

    app.use(express.static(process.argv[3]||path.join(__dirname, 'public')));</div>

})

Now, a couple things.  First, I assigned process.argv[3] to the variable filePath so I changed that.  The second thing was that path as in path.join(__dirname etc), was undefined.  A little googling showed me that path is a node package, so we need to require it.  That gave me:

var express = require('express');
var path = require('path');
var port = process.argv[2];
var filePath = process.argv[3];

app.get('/home', function(req, res) {
     app.use(express.static(filePath||path.join(__dirname, 'public')));
})

But that didn’t work.  A closer examination showed me that app.get() and app.use() are two different methods.  So I get rid of the app.get() framework and just left the app.use statement there:

express = require('express');
var path = require('path');
var port = process.argv[2];
var filePath = process.argv[3];

var app = express()</div>
     app.use(express.static(filePath||path.join(__dirname, 'public')));
app.listen(port);

 

Bazinga!  It worked!

And that’s it for today.  See you next time!

One thought on “Free Code Camp and Learning Express.js: Static

Leave a comment