从零开始学习Node.js系列教程四:多页面实现的数(2)

var htutil = require('./htutil'); var math = require('./math'); function sendResult(req, res, a, fiboval){ res.writeHead(200, {'Content-Type': 'text/html'}); res.end( htutil.page("Fibonacci", htutil.navbar(), [ (!isNaN(fiboval) ? ("<p>{a} fibonacci = {fibo}</p>" .replace("{a}", a) .replace("{fibo}", fiboval)) : ""), "<p>Enter numbers to see its fibonacci</p>", "<form action='https://www.jb51.net/fibonacci' method='get'>", "A: <input type='text' /><br/>", "<input type='submit' value='Submit' />", "</form>" ].join('\n')) ); } exports.get = function(req, res){ if (!isNaN(req.a)){ math.fibonacciAsync(Math.floor(req.a), function(val){ sendResult(req, res, Math.floor(req.a) ,val); }); }else { sendResult(req, res, NaN, NaN); } }

math.js

var factorial = exports.factorial = function(n){ if (n == 0) return 1; else return n * factorial(n-1); } 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); } var fibonacciAsync = exports.fibonacciAsync = function(n, done){ if (n ==1 || n == 2) done(1); else { process.nextTick(function(){ fibonacciAsync(n-1, function(val1){ process.nextTick(function(){ fibonacciAsync(n-2, function(val2){ done(val1 + val2); }); }) }); }); } }

从零开始学习Node.js系列教程四:多页面实现的数

 

从零开始学习Node.js系列教程四:多页面实现的数

 

从零开始学习Node.js系列教程四:多页面实现的数

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyppzf.html