Select Page

More Node.js troubles, would you believe it?! But there’s always a solution.

I’m finally getting to the more interesting part of my Node.js Lynda course (Node.js First Look) where we’re actually building http servers. It’s really pretty amazing and exciting that running a js script from the command line can suddenly make your computer serve you data at whatever port you specify, and I’m really looking forward to being able to use this stuff in the real world.

Screen Shot on 2016-01-20 at 08-07-47We’re using the Connect Node module to simplify web server creation (even though it’s ridiculously simple already), but Mr. LeBlanc was writing for an older version of Connect while I was using the current one, and that of course caused problems that made node throw errors every time I tried to run my server script:
Error: Cannot find module 'serve-static'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:289:25)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object. (/Users/jonathanmccormick/Google Drive/Projects/Learn NodeJS/server/server.js:2:19)
at Module._compile (module.js:435:26)
at Module._extensions..js (module.js:442:10)
at Object.nodeDevHook [as .js] (/usr/local/lib/node_modules/node-dev/lib/hook.js:43:7)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
[ERROR] 07:58:51 Error

As always, a quick Google search turned up a solution. Apparently newer versions of Node (3.x) have moved the static middleware to it’s own module, so you’ll need to install it separately in addition to the regular connect module. Simply run npm install serve-static in your project’s folder and then require it in your code. Now my code looks like this:
var connect = require('connect'),
serveStatic = require('serve-static');
var app = connect()
.use(serveStatic('public'))
.use(function (req, res) {
res.end("Oops, couldn't find it :/");
})
.listen(3000);
HAHA!! It works.