一个简单的nodeJS实现

一个简单的nodeJS实现_第1张图片这是目录结构
app-node.js
/**
 * @author Administrator
 * 请求的路由选择
 */
var http_port = 8124;

var http = require('http');
var htutil = require('./htutil');

var server = http.createServer( function(req, res){
	htutil.loadParams(req, res, undefined);
	if(req.requrl.pathname === '/'){
		require('./home-node').get(req, res);
	}else if(req.requrl.pathname === '/square'){
		require('./square-node').get(req, res);
	}else if(req.requrl.pathname === '/fibo'){
		require('./fibo-node').get(req, res);
	}else {
		res.writeHead(404, {'Content-Type':'text/plain'});
		res.end('bad URL ' + req.url);
	}
});

server.listen(http_port);
console.log('listening to http://localhost:8124');

home-node.js
var htutil = require('./htutil');

exports.get = function(req, res){
	res.writeHead(200, {'Content-Type':'text/html'});
	res.end(
		htutil.page('home', 
		htutil.navbar(), 
		" 

home

" ) ); }


htutil.js

/*
 * 处理URL查询参数
 */
var url = require('url');

exports.loadParams = function(req, res, next){
	req.requrl = url.parse(req.url, true);
	req.a = (req.requrl.query.a && ! isNaN(req.requrl.query.a))
		? new Number(req.requrl.query.a)
		: NaN;
	req.b = (req.requrl.query.b && !isNaN(req.requrl.query.b))
		? new Number(req.requrl.query.b)
		: NaN;
	if(next) next();
}
//这个函数提供了一个HTML片段,可以作为一个导航栏
exports.navbar = function(){
	return ["
", "

home

", "

square

", "

factorial

", "
"].join('\n'); } //这个函数对用整个页面的HTML结构 exports.page = function(title, navbar, content){ return ["{title}", "

{navbar}

{content}"].join('\n') .replace("{title}", title, "g") .replace("{navbar}", navbar, "g") .replace("{content}", content, "g"); }

square-node.js
//计算一个数的平方并显示

var htutil = require('./htutil');

exports.get = function(req, res){
	res.writeHead(200, {'Content-Type':'text/html'});
	res.end(
		htutil.page('square', htutil.navbar(), [
				(!isNaN(req.a)? 
					("

{a} aquare = {sq}

".replace("{a}", req.a).replace("{sq}", req.a*req.a)) : "" ), "

entet a number to see its square

", "
", "A: ", "
" ].join('\n')) ); }

fibo-node.js
var htutil = require('./htutil');
var math = require('./math');

exports.get = function(req, res){
	res.writeHead(200, {'Content-Type':'text/html'});
	res.end(
		htutil.page('square', htutil.navbar(), [
				(!isNaN(req.a)? 
					("

{a} fibo = {fibo}

".replace("{a}", Math.floor(req.a)).replace("{fibo}", math.fibonacci(Math.floor(req.a)))) : "" ), "

entet a number to see its fibonacci

", "
", "A: ", "
" ].join('\n')) ); }

math.js
var fibonacci = exports.fibonacci = function(n){
	if(n === 1)
		return 1;
	else if(n === 2)
		return 1;
	else 
		return fibonacci(n-1) + fibonacci(n-2);
}



运行结果:
一个简单的nodeJS实现_第2张图片






你可能感兴趣的:(NodeJS)