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
.
Written by Eric Allam
Related protips
1 Response
There are also node_module
s built specifically for this purpose.
npm install -g serve
serve
# Server now running at localhost:3000
# with automatic Jade + Stylus rendering
[grunt][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.
[grunt]: https://github.com/gruntjs/grunt/
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Nodejs
Authors
Related Tags
#nodejs
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#