nodejs 入门教程笔记
转载一篇nodejs入门比较好的教程:
http://www.nodebeginner.org/index-zh-cn.html
本文为了自己的学习方便,做一下简略的笔记.
代码的模块需要组织,为此建立起一个index.js用来调用别的模块
1."http"模块(server.js)
var http = require("http");
...
http.createServer(...);//函数里可以接受匿名函数,也可以接受函数变量
function onRequest(request, response) { console.log("Request received."); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }
var http = require("http"); function start() { function onRequest(request, response) { console.log("Request received."); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start;//至此server.js模块便完成了
2.路由模块(router.js)
对于不同的url请求(包括其他需要的GET及POST参数),服务器应该有不同的反应.
为此,我们需要去查看HTTP请求,从中提取出请求的URL以及GET/POST参数.
为了解析这些数据,需要引入额外的Node.JS模块,分别是url和querystring模块.
function route(pathname){ console.log("About to route a request for "+pathname); } exports.route = route;
接下来把服务器和路由整合起来.
3.请求处理程序模块(requestHandlers.js)
参见引用的源地址.
4.阻塞与非阻塞
要用非阻塞操作,我们需要使用回调,通过将函数作为参数传递给其他需要花时间做处理的函数();
需要引入一个新的Node.js模块.
var exec = require("child_process").exec;
待修改...