nodejs 入门

1. 一个简单的粒子

我看很多教程都用这个

1
2
3
4
5
6
7
var http = require("http")

http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type":"text/plain"});
response.write("Hello world");
response.end();
}).listen(8888)

require函数中的参数如果是模块名,那么返回这个模块,如果是文件路径,那么将返回该文件。

createServer在这里创建一个服务,监听888端口

也可以分为两个文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 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);
}

exports.start = start;

index.js中使用server模块

1
2
3
4
// index.js
var server = require("./server");

server.start();

2. 设置请求的路由

在这里我们需要引入url这个模块。

1
var pathname = url.parse(request.url).pathname;

此外重写route模块

1
2
3
4
function route(pathname) {
console.log("About to route a request for " + pathname);
}
exports.route = route;
1
2
3
4
5

var server = require("./url");
var route = require("./route")

server.start(route.route);

随后就能在终端下看到请求的信息

1
2
3
4
5
6
7
8
9
server end
Request for /12received
About to route a request for /12
Request for /favicon.icoreceived
About to route a request for /favicon.ico
Request for /myblogreceived
About to route a request for /myblog
Request for /favicon.icoreceived
About to route a request for /favicon.ico

3. 路由进行事务处理

之前我们是进行了请求,但是没有进行真正的处理。

1
2
3
4
5
6
7
8
9
10
function route(handle, pathname) {
console.log("The pathname is " + pathname);
if (typeof handle[pathname] == 'function') {
handle[pathname]();
} else {
console.log("No request handle for the " + pathname);
}
}

exports.route = route

当我们的filename是所需的路径,直接使用handle函数进行处理。