这篇博文主要是学习利用node的核心模块http构建类似Apache的服务器效果,以及在node中使用art-template模板引擎,最后做一个类似Apache读取文件目录的效果。

2.1 http构建类似Apache的服务器效果

  • 2.1.1 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const fs = require('fs');
const http = require('http');

//Apache 服务器软件默认有一个 www 目录
//所有存放在 www 目录中的资源都可以通过网址来浏览,我们创建一个类似的测试目录
const testPath = 'd:/NodeTest/www';

let server = http.createServer();
//监听request请求事件,一个请求对应一个响应,没有请求就没有响应
//如果在一个请求的过程中,已经结束响应了,则不能重复发送响应。
server.on('request', function (req, res){
let url = req.url;
let filePath = '/index.html';
if(url !== '/'){
filePath = url;
}

fs.readFile(testPath+filePath, function (err, data){
if(err){
//return 有两个作用:1.方法返回值 2.阻止代码继续往后执行
return res.end('404 No Fond')
}else{
res.end(data)
}
})
});

server.listen(3000, function (){
console.log('server is running....');
});

2.2 在Node中使用模板引擎 art-template

  • 2.2.1 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// npm install art-template
// 该命令在哪执行就会把包下载到哪里。默认会下载到 node_modules 目录中

// 在 Node 中使用 art-template 模板引擎
// 1. 安装 npm install art-template
// 2. 在需要使用的文件模块中加载 art-template 加载方法require('art-template')
// 参数中的 art-template 就是你下载的包的名字
// 3. 查文档,使用模板引擎的 API
const template = require('art-template');
const fs = require('fs');

fs.readFile('./tpl.html', function (err, data){
if(err){
return console.log('Not Find tpl.html');
}

//注意,readFile读取的data是二进制的,template需要的时字符串所以要data.toString()
let ret = template.render(data.toString(), {
title: 'i am title',
name: 'jack',
age: 18,
province: 'beijing',
hobbies: ['eat', 'play', 'code']
});

console.log(ret);
});
  • 2.2.2 注意
1
2
//强调:模板引擎不关心你的字符串内容,只关心自己能认识的模板标记语法,例如 {{ value }}
//这种 {{ value }} 语法被称之为 mustache 语法。
  • 2.2.3 打印效果对比