Moving on, here’s the next exercise in the FreeCodeCamp Express tutorial, Static. The directions and hints:
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”