Simple static node.js server, no external files loading

Problem

Using this simple static node.js server https://github.com/jesusabdullah/node-ecstatic

and created a stock http server

var http = require('http');
var ecstatic = require('ecstatic');

http.createServer(
  ecstatic({ root: __dirname + '/index.html' })
).listen(8080);

console.log('Listening on :8080');

After starting my server, the index.html loads correctly but none of my external scripts or CSS load. Only 404's

The pathing is correct and all relative to the index.html. The 'js' folder is in the same directory as my index.html

<script src ="js/foo.js"></script

Can anyone suggest why this is happening?

Problem courtesy of: eco_bach

Solution

You identify the root directory in your call to ecstatic, not the single file you're serving.

So assuming your node.js file is in the same directory as index.js, the call should look like:

http.createServer(
  ecstatic({ root: __dirname })
).listen(8080);

Note that this would let people download your node.js file as well, which is why people usually put their static files off in a separate directory like public instead.

Solution courtesy of: JohnnyHK

Discussion

Change <script src ="js/foo.js"></script> to <script src ="/js/foo.js"></script>. Does this work?

Where are your external scripts or css placed?

From ecstatic readme;

app.use(ecstatic({ root: __dirname + '/public' }));

This defines the root dir of the static server, your definition of root to __dirname + '/index.html' is incorrect, just use app.use(ecstatic({ root: __dirname })); if current folder contains all your static assets.

Discussion courtesy of: vmx

This recipe can be found in it's original form on Stack Over Flow.