使用node实现简单的apache功能
1.实现根据文件名(路径)访问到指定文件
1.思路的话:在指定的文件里面创建
例如:我在c:/inetpub/www/ 里面创建了如下三个文件
需要在客户端访问时输入对应的文件名例如:http://127.0.0.1:3000/index.html就会定位到对应的文件,如果没有对应的文件,则返回404
const http = require('http');
const fs = require('fs');
const server = http.createServer();
//定义成全局的方便修改
const BASE = 'c:/inetpub/www';
server.on('request',(req,res)=>{
console.log('客户端已连接',req.url);
const url = req.url;
let filePath = '/index.html';
if(url !== '/'){
filePath = url;
}
//读对应文件
fs.readFile(BASE+filePath,(err,data)=>{
if(err){
return res.end('404 Not Found');
}
//指定文件在网页上显示的格式,例如有中文需要指定utf-8,图片需要把image/jpeg,网页的是text/html,其他格式的文件也有对应的格式
res.setHeader('Content-Type','text/plain; charset=utf-8')
res.end(data);
})
})
server.listen(5000,()=>{
console.log('服务器已开启请访问:http://127.0.0.1:3000')
})
2.实现目录的效果
当读取的www目录中没有index.html这个文件是就是出现一个目录,如下:
想要实现这个效果呢需要需要在服务器端渲染这个页面,目录里面的数据可以通过
const fs = require('fs');
fs.readDir(path,(err,data) => {
console.log(data) //[...]
})
然后可以通过字符串拼接的形式,使用一个String.replace()方法渲染出来这个页面,当然也可以使用模板引擎来渲染,这里举例为使用art-template
npm install art-template --save
加载这个包,然后在对应页面写好其格式
<html>
<head>
<title></title>
</head>
<body>
{{each files}}
...str...{{$value}}...
{{/each}}
</body>
</html>
最后在js文件中设置一下就ok了