rbghmg
Last Updated: February 25, 2016
·
3.17K
· eallam
Ericprofilenew

Create a simple static file server with Node.js and Filed

If you have an HTML file and some js/css that you want to serve up over localhost (because of the dreaded Uncaught Error: SECURITY_ERR: DOM Exception 18 error when opening a file:// in Chrome) you can do so pretty easily using node.js and the filed module. Put your html/css/js/image files in public and then create app.js in the same dir as public:

var http = require('http'),
    filed = require('filed');

server = http.createServer(function(req, resp){
  if(req.url === "/"){
    req.pipe(filed('./public/index.html')).pipe(resp);
  }else{
    req.pipe(filed("./public" + req.url)).pipe(resp);
  }
});

var port = process.argv[2] || 8080

server.listen(port, function(){
  console.log("Server started on " + port);
});

Now all you have to do is run app.js like so:

$ node app.js 3000
Server started on 3000

Make sure you put your "homepage" HTML file in public/index.html.

Say Thanks
Respond

1 Response
Add your response

4194
15927fc52919e9223adc7ed99e125d4d

There are also node_modules built specifically for this purpose.

npm install -g serve
serve
# Server now running at localhost:3000
# with automatic Jade + Stylus rendering

grunt also has a serve task but in the transition to 0.4 there are a few too many steps to follow to get this set up.

over 1 year ago ·