Create TOC

2013년 7월 1일

nodejs/sample

간단한 node.js sample.

var url = require('url');
var domain = require('domain');
var fs = require('fs');

require('http').createServer(function(req, res) {
	var u = url.parse(req.url, true);
	if (u.pathname == '/error') {
		if (u.search == '') {
			res.writeHead(200);
			res.write('<html><title>error</title></head><body>error</body></html>');
		}
		else {
			res.writeHead(u.query.e);
			res.write('<html><title>error</title></head><body>' + u.query.e + '</body></html>');
		}
		res.end();
	}
	else {
		if (u.pathname == '/') {
			u.pathname = '/index.html';
		}
		var d = domain.create();
		d.run(function() {
			fs.readFile(__dirname + '/public_html'+ u.pathname, d.intercept(function(data) {
				res.writeHead(200);
				res.write(data, 'utf8');
				res.end();
			}));
		});

		d.on('error', function(err) {
			console.log(err);
			var errpage = '/error';

			if (err.errno == 34) {
				errpage = errpage + '?e=404';
			}
			res.writeHead(302, {'Location': errpage});
			res.end();
		});
	}
}).listen(1234);