Home  >  Article  >  Web Front-end  >  轻松创建nodejs服务器(2):nodejs服务器的构成分析_node.js

轻松创建nodejs服务器(2):nodejs服务器的构成分析_node.js

WBOY
WBOYOriginal
2016-05-16 16:25:54928browse

紧接上一节,我们来分析一下代码:

第一行请求(require)Node.js自带的 http 模块,并且把它赋值给 http 变量。

接下来我们调用http模块提供的函数: createServer 。

这个函数会返回一个对象,这个对象有一个叫做 listen 的方法,这个方法有一个数值参数,指定这个HTTP服务器监听的端口号。

为了提高可读性,我们来改一下这段代码。

原来的代码:

复制代码 代码如下:

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

可以改写成:

复制代码 代码如下:

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

我们定义了一个onRequest()函数,并将它作为参数传给createServer,类似回调函数。

我们给某个方法传递了一个函数,这个方法在有相应事件发生时调用这个函数来进行回调,我们把这叫做基于事件驱动的回调。

接下来我们看一下onRequest() 的主体部分,当回调启动,我们的 onRequest() 函数被触发的时候,有两个参数被传入: request 和 response 。

request : 收到的请求信息;

response : 收到请求后做出的响应。

所以这段代码所执行的操作就是:

当收到请求时,

1、使用 response.writeHead() 函数发送一个HTTP状态200 和 HTTP头的内容类型(content-type)

2、使用 response.write() 函数在HTTP相应主体中发送文本“Hello World”。

3、调用 response.end() 完成响应。

这样分析,是不是加深了你对这段代码的理解呢?

下一节我们来了解一下,nodejs的代码模块化。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn