nodejs - 创建服务器(1)

在此之前,确保你已经安装了Node(并且你很会折腾) - 有人说,Java脚本和Java最本质的区别就是一个超会更新,一个死守旧。

如果你没有安装,请去官网下载并且安装:http://nodejs.cn/download/

中文文档:http://nodejs.cn/api/

 

 

先来说说node的优点以及缺点

粗略的来说node的优点即在于它是单线程、运行环境要求低,缺点同样明显的就是它一旦出现问题,全部瘫痪。

而php和java是多线程运行的,互不影响,但占资源高。

 

看一个小例子(菜鸟教程里面的)

 1 var http = require('http');
 2 
 3 http.createServer(function(request, response) {
 4 
 5     // 发送 HTTP 头部 
 6     // HTTP 状态值: 200 : OK
 7     // 内容类型: text/plain
 8     response.writeHead(200, { 'Content-Type': 'text/plain' });
 9 
10     // 发送响应数据 "Hello World"
11     response.end('Hello World\n');
12 }).listen(8888);
13 
14 // 终端打印如下信息
15 console.log('Server running at http://127.0.0.1:8888/');

 

 1 // 请求http包
 2 var http = require('http');
 3 
 4 // 创建一个http线程
 5 http.createServer(function(request, response) {
 6 
 7     // 发送 HTTP 头部 
 8     // HTTP 状态值: 200 : OK
 9     // 内容类型: text/plain
10     response.writeHead(200, { 'Content-Type': 'text/plain' });
11 
12     // 发送响应数据 "Hello World"
13     response.end('Hello World\n');
14 }).listen(8888);
15 
16 // 终端打印如下信息
17 console.log('Server running at http://127.0.0.1:8888/');

 

很好,可以运行

默认本地:127.0.0.1

端口自设:8088

 

我们看看官网API(http自带server)

且每一段代码都会带上res.end() , 这是因为我们要告诉服务器已经完成了.

再来看看这一段代码

 1 var http = require('http');
 2 var fs = require('fs');
 3 
 4 var server = http.createServer(function(req, res) {
 5 
 6     // 请求路由 ==是指字符串比较
 7     if (req.url == "/index") {
 8         fs.readFile('index.html', function(err, data) {
 9             res.writeHead(200, { "Content-type": "text/html;charset=utf-8" });
10             res.end(data);
11         });
12     } else {
13         fs.readFile('404.html', function(err, data) {
14             res.writeHead(200, { "Content-type": "text/html;charset=utf-8" });
15             res.end(data);
16         });
17     }
18 });
19 
20 server.listen(80, '127.0.0.1');
 1 // 导入http
 2 var http = require('http');
 3 // 导入fs(文件读取服务)
 4 var fs = require('fs');
 5 
 6 var server = http.createServer(function(req, res) {
 7     // 其实nodejs最难的一点就是管理路由 - 它和其它web服务器不一样(因此灵活性超强)
 8 
 9     // 请求路由 ==是指字符串比较
10     if (req.url == "/index") {
11         // 请求地址index,读取文件index.html
12         fs.readFile('index.html', function(err, data) {
13             res.writeHead(200, { "Content-type": "text/html;charset=utf-8" });
14             res.end(data);
15         });
16     } else {
17         // 请求地址不存在,读取文件404.html,并且返回
18         fs.readFile('404.html', function(err, data) {
19             // 请求头 - 根据类型不同而不同
20             res.writeHead(200, { "Content-type": "text/html;charset=utf-8" });
21             res.end(data);
22         });
23     }
24 });
25 
26 // 监听80端口,并且是本地地址
27 server.listen(80, '127.0.0.1');

 

通过 localhost/index 就可以访问到

index.html了。

通过localhost/other 就可以访问到

其它页面了。

你试一试链接本地图片或者css以及其它资源,感受一下node路由的强大!

 

猜你喜欢

转载自www.cnblogs.com/cisum/p/9270580.html