2
\$\begingroup\$

Being new to Node.js, I'd like to know of a better way of implementing this:

server = http.createServer( function(req, res) {
if (req.url === '/') {
 fs.readFile('index.html', function(err, page) {
 res.writeHead(200, {'Content-Type': 'text/html'});
 res.write(page);
 res.end();
 });
} 
 else if (req.url == '/new.html') { 
 fs.readFile('new.html', function(err, page) {
 res.writeHead(200, {'Content-Type': 'text/html'});
 res.write(page);
 res.end();
 });
}
});
server.listen(8080);

Using something like this:

var Url = require('url')
...
// In request handler
var uri = Url.parse(req.url);
switch (uri.pathname) {
 case "/":
 ..
 case "/new.html":
 ..
}
asked Dec 31, 2011 at 16:57
\$\endgroup\$
3
  • \$\begingroup\$ Use a router like express. \$\endgroup\$ Commented Dec 31, 2011 at 17:33
  • 1
    \$\begingroup\$ Other than using a framework... \$\endgroup\$ Commented Dec 31, 2011 at 23:30
  • \$\begingroup\$ If you want static routing you can write a naive static router \$\endgroup\$ Commented Jan 1, 2012 at 10:48

1 Answer 1

2
\$\begingroup\$

Whether you wanna implement a static server? If so, you can just use connect and its built-in static middlewave. With it, you just need to write the following code to implement a static server:

var connect = require("connect");
connect(
 connect.static(__dirname)
).listen(3000);

That's it.

answered Jan 6, 2012 at 7:07
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.