如何使用Node.js做一个Apache 服务器

我们以前使用过 Apache 服务器软件,这个软件默认有一个 www 目录,所有存放在 www 目录中资源都可以通过网址来浏览。那么如何使用Node.js做一个Apache 服务器呢?

思路:
1、得到www文件下面的文件名和目录名
2、将得到的文件名和目录名替换到template.html中
3、发送解析执行之后的html页面

解决方法:
我们可以用fs.readdir得到www文件下面的文件名和目录名。

在template.html中需要替换的位置预留一个特殊的标记,用replace替换要插入的数据

response.end(data)方法发送解析执行之后的html页面

代码如下:
js代码:


var http = require('http');
var fs = require('fs');

//1、创建server
var server = http.createServer();

//2、监听Server的request请求事件,请求处理函数
//   请求
//     处理
//   响应
//一个请求对应一个响应,如果在一个请求的过程中,已经结束响应了,则不能重复发送响应
//没有请求就没有响应

//我们以前使用过 Apache 服务器软件,这个软件默认有一个 www 目录,所有存放在 www 目录中资源都可以通过网址来浏览
//127.0.0.1:3000/a.txt
//127.0.0.1:3000/index.html
//127.0.0.1:3000/apple/login.html

var wwwDir = 'C:\\Users\\18236\\Desktop\\web前端学习\\www'

server.on('request',function (req,res){
    
    
    var url = req.url;

   fs.readFile('./template.html',function (err,data){
    
    
       if(err){
    
    
         return  res.end('404 not found');
       }else{
    
    
           //1、如何得到wwwDir的文件名和目录名
           // fs.readdir
           fs.readdir(wwwDir,function (err,files){
    
    
               if(err){
    
    
                   return res.end('Can not find www dir');
               }
               console.log(files);
               //2、如何将得到的文件名和目录名替换到template.html中
               //2.1 在template.html中需要替换的位置预留一个特殊的标记(就像以前使用模块引擎的标记一样)
               //2.2 根据files 生成需要的 HTML 内容

               var content = '';
               files.forEach(function (item){
    
    
                   //ECMAScript 6中的``字符串中,可以用${}来引用变量
                   content +=`
             <tr>
                <td><a href="">${
      
      item}</a></td>
                <td></td>
                <td>2020/10/7 下午17:48:00</td>
             </tr>
             `;

               });

               //2.3替换
               data = data.toString();

               //普通的字符串解析替换,浏览器看到的结果不一样
               data = data.replace(' ^_^',content)
               // console.log(data);

               //3、发送解析执行之后的html页面
               res.end(data);

           })





       }
   })


})

//3、绑定端口号,启动服务器
server.listen(3000,function (){
    
    

    console.log('服务器启动了...');
})

template.html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        table th,td{
    
    
            width: 100px;
            text-align: center;
        }
        table th:nth-child(3),td:nth-child(3){
    
    
            width: 200px;
            text-align: center;
        }
    </style>
</head>
<body>
<h3>C:/User/18236</h3>
<hr>
<table>
    <thead>
    <tr>
        <th>名称</th>
        <th>大小</th>
        <th>修改日期</th>
    </tr>
    </thead>
    <tbody>
   ^_^
    </tbody>
</table>
</body>
</html>

执行结果:
在这里插入图片描述
结果与文件内容一致。

猜你喜欢

转载自blog.csdn.net/cake_eat/article/details/108955697