找一份好的教材: http://www.nodebeginner.org/index-zh-cn.html
它太棒了,通俗易懂,不过我还是把他按我的理解记录,也许比原来更好理解,也许相反。
1.得先会helloworld,准备运行环境,安装node.js,参考
运行第一个nodejs程序
//helloworld.js
console.log("Hello World");
在终端,运行node helloworld.js
我们知道这是在服务器段运行的模式,这可不是nodejs的初衷,我们要如何才能用http的模式运行呢?
2.搭建简单的WEB SERVER(server.js)
//server.js //nodejs内置的require模块
var http = require("http");
//调用createServer方法
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
先启动Web服务器(看起来有点像):node server.js
这样当前服务器的8888端口被监听了
当在Browser中访问: http://localhost:8888
即产生请求,那就会被回应(response):Hello World
如何,简单的WEB Server建立起来了,似乎可以处理任何请求,不过你等到的都是“Hello World”;
当然为了解决这个问题,我们需要处理更多的功能,在进入前,我们先来了解一下nodejs关于模块的定义。
3.为了代码模块化,我们需要会建立自定义的nodejs模块
我们来稍微加点东西:exports
//server.js
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;
然后我们可以这样在另一个JS文件中当作模块一样所以他们:
//index.js
var server = require("./server");
server.start();
这就是模块的定义与引用,我们将index.js与server.js关联起来了,模块的可爱模样应用初现身影。
我们也为开发更多的功能做好了最基本的准备。
接下来我们要将我们的WEB Server打扮得更像一些。
我们来一个假设,如果你的每次请求都得到“hello world",你可能会认为那是个疯子,应该是不同的请求有不同的回应,这是最基本的。
所以,我们需要在服务端将不同的请求进行不同的处理---我们加入路由功能
当然,我们需要使用上面刚学到的技巧:使用自定义模块的形式来组织代码文件
//router.js
function route(pathname) {
console.log("About to route a request for " + pathname);
}
exports.route = route;
可以看出,他什么都没有做,除了log一段信息之外。