Nodejs乘法平方例子

此例实现的功能如下图所示

Nodejs乘法平方例子_第1张图片

Nodejs乘法平方例子_第2张图片

Nodejs乘法平方例子_第3张图片

计算结果

Nodejs乘法平方例子_第4张图片

Nodejs乘法平方例子_第5张图片

代码如下

app-node.js

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

function onRequest(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==='/mult')
	{
		require('./mult-node').get(req,res);
	}
	else
	{
		res.writeHead(404,{'Content-Type':'text/plain'});
		res.end("bad URL"+req.url);
	}
	
}

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

htutil.js

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();
}
//导航条
exports.navbar=function()
{
	return [""].join('\n');
}

exports.page=function(title, navbar, content)
{
	return ["{title}",
			"

[title]

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

home-node.js

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

Math Wizard

") ); }

mult-node.js

var htutil=require('./htutil');
exports.get=function(req, res)
{
res.writeHead(200,{'Content-Type':'text/html'});
var result=req.a*req.b;
var strT="

{a}*{b}={result}

"; strT=strT.replace("{a}", req.a); strT=strT.replace("{b}", req.b); strT=strT.replace("{result}", result); var resultStr=(!isNaN(req.a)&&!isNaN(req.b))?strT:""; res.end( htutil.page("Multiplication", htutil.navbar(), [resultStr, "

Enter numbers to multiply

", "
", "A:
", "B:
", "", "
"].join('\n') ) ); }
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} squared = {sq}

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

Enter a number to see its square

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

参考书籍《Node Web Development》


你可能感兴趣的:(node.js)