nodejs仿写Apache htdocs文件

在这里插入图片描述
首先自己先在随便什么盘创建一个文件夹来装文件或文件夹,这里我在c盘创建了一个app文件夹
下面写页面部分,给些特殊的字符到时候去替换内容

<html>
<head>    
	<meta charset="utf-8">    
	<style>        
		h1 {            
			border-bottom: 1px solid #c0c0c0;            
			margin-bottom: 10px;            
			padding-bottom: 10px;            
			white-space: nowrap;        
		}
		table {  
			border-collapse: collapse;        
		}
		a.icon {            
			-webkit-padding-start: 1.5em;            
			text-decoration: none;        
		}
		a.icon:hover {            
	        	text-decoration: underline;        
	     	}
		a.file {            
	        	background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABnRSTlMAAAAAAABupgeRAAABHUlEQVR42o2RMW7DIBiF3498iHRJD5JKHurL+CRVBp+i2T16tTynF2gO0KSb5ZrBBl4HHDBuK/WXACH4eO9/CAAAbdvijzLGNE1TVZXfZuHg6XCAQESAZXbOKaXO57eiKG6ft9PrKQIkCQqFoIiQFBGlFIB5nvM8t9aOX2Nd18oDzjnPgCDpn/BH4zh2XZdlWVmWiUK4IgCBoFMUz9eP6zRN75cLgEQhcmTQIbl72O0f9865qLAAsURAAgKBJKEtgLXWvyjLuFsThCSstb8rBCaAQhDYWgIZ7myM+TUBjDHrHlZcbMYYk34cN0YSLcgS+wL0fe9TXDMbY33fR2AYBvyQ8L0Gk8MwREBrTfKe4TpTzwhArXWi8HI84h/1DfwI5mhxJamFAAAAAElFTkSuQmCC ") left top no-repeat;        
	        }
		a.dir {            
			background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAd5JREFUeNqMU79rFUEQ/vbuodFEEkzAImBpkUabFP4ldpaJhZXYm/RiZWsv/hkWFglBUyTIgyAIIfgIRjHv3r39MePM7N3LcbxAFvZ2b2bn22/mm3XMjF+HL3YW7q28YSIw8mBKoBihhhgCsoORot9d3/ywg3YowMXwNde/PzGnk2vn6PitrT+/PGeNaecg4+qNY3D43vy16A5wDDd4Aqg/ngmrjl/GoN0U5V1QquHQG3q+TPDVhVwyBffcmQGJmSVfyZk7R3SngI4JKfwDJ2+05zIg8gbiereTZRHhJ5KCMOwDFLjhoBTn2g0ghagfKeIYJDPFyibJVBtTREwq60SpYvh5++PpwatHsxSm9QRLSQpEVSd7/TYJUb49TX7gztpjjEffnoVw66+Ytovs14Yp7HaKmUXeX9rKUoMoLNW3srqI5fWn8JejrVkK0QcrkFLOgS39yoKUQe292WJ1guUHG8K2o8K00oO1BTvXoW4yasclUTgZYJY9aFNfAThX5CZRmczAV52oAPoupHhWRIUUAOoyUIlYVaAa/VbLbyiZUiyFbjQFNwiZQSGl4IDy9sO5Wrty0QLKhdZPxmgGcDo8ejn+c/6eiK9poz15Kw7Dr/vN/z6W7q++091/AQYA5mZ8GYJ9K0AAAAAASUVORK5CYII= ") left top no-repeat;        
		}
		a.up {            
			background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAmlJREFUeNpsU0toU0EUPfPysx/tTxuDH9SCWhUDooIbd7oRUUTMouqi2iIoCO6lceHWhegy4EJFinWjrlQUpVm0IIoFpVDEIthm0dpikpf3ZuZ6Z94nrXhhMjM3c8895977BBHB2PznK8WPtDgyWH5q77cPH8PpdXuhpQT4ifR9u5sfJb1bmw6VivahATDrxcRZ2njfoaMv+2j7mLDn93MPiNRMvGbL18L9IpF8h9/TN+EYkMffSiOXJ5+hkD+PdqcLpICWHOHc2CC+LEyA/K+cKQMnlQHJX8wqYG3MAJy88Wa4OLDvEqAEOpJd0LxHIMdHBziowSwVlF8D6QaicK01krw/JynwcKoEwZczewroTvZirlKJs5CqQ5CG8pb57FnJUA0LYCXMX5fibd+p8LWDDemcPZbzQyjvH+Ki1TlIciElA7ghwLKV4kRZstt2sANWRjYTAGzuP2hXZFpJ/GsxgGJ0ox1aoFWsDXyyxqCs26+ydmagFN/rRjymJ1898bzGzmQE0HCZpmk5A0RFIv8Pn0WYPsiu6t/Rsj6PauVTwffTSzGAGZhUG2F06hEc9ibS7OPMNp6ErYFlKavo7MkhmTqCxZ/jwzGA9Hx82H2BZSw1NTN9Gx8ycHkajU/7M+jInsDC7DiaEmo1bNl1AMr9ASFgqVu9MCTIzoGUimXVAnnaN0PdBBDCCYbEtMk6wkpQwIG0sn0PQIUF4GsTwLSIFKNqF6DVrQq+IWVrQDxAYQC/1SsYOI4pOxKZrfifiUSbDUisif7XlpGIPufXd/uvdvZm760M0no1FZcnrzUdjw7au3vu/BVgAFLXeuTxhTXVAAAAAElFTkSuQmCC ") left top no-repeat;        
		}
		#parentDirLinkBox {           
	 		margin-bottom: 10px;            
	 		padding-bottom: 10px;        
	 	}    
	</style>    
	<title id="title">Index Of{{path}}</title>
</head>
<body>    
	<h1 id="header">Index Of/{{path}}</h1>    
	<div id="parentDirLinkBox" {{display}}>        
		<a id="parentDirLink" class="icon up" href="{{parentPath}}">            
			<span id="parentDirText">[上级目录]</span>        
		</a>    
	</div>    
	<table>        
		<tbody id="tbody">^_^</tbody>    
	</table>
</body>
</html>

创建一个config的js文件写入一些配置信息,方便后面使用

module.exports = {    
	port : 3000, // 服务器端口号    
	documentRoor : "C:/app", // 根目录  这是自己开始创建放文件的文件夹路径
	directoryBrowse : true, // 是否开启目录浏览功能    
	// 目录默认访问页    
	directoryIndex : [        
		'index.html',        
		'index.htm',        
		'deflaut.html'    
	],    
	charset : 'utf-8',    
	mineType : { //文件类型        
		image: {            
			gif: 'image/gif',            
			jpeg: 'image/jpeg',            
			jpg: 'image/jpeg',            
			png: 'image/png'        
		},        
		text: {            
			css: 'text/css',            
			html: 'text/html',            
			htm: 'text/htm',            
			js: 'application/x-javascript',            
			json: 'application/json',            
			pdf: 'application/pdf',        
		},        
		other: 'text/plain'    
	}
}

创建一个服务器代码app.js,这个文件开启一个http服务,实现了apache的目录浏览和部分类型文件的查看功能

// 引入模块
const http = require("http");
const fs = require("fs");
const path = require("path");
const config = require("./config"); //引入配置文件

//根目录
const documentRoor = config.documentRoor;
// 引入服务
const server = http.createServer();

//监听request
server.on('request',(req,res)=>{    
	let url = req.url; //地址    
	let tmp = documentRoor + url; //目录路径    
	let exitst = fs.existsSync(tmp); //检查根目录路径是否存在    
	if(exitst || url != '/favicon.ico' || url == '/'){        
		let stats1 = fs.statSync(tmp); //查看文件详细信息        
		if(stats1.isDirectory()){//如果是文件夹返回true            
			if(!config.directoryBrowse){//如果没有开启目录浏览功能                
				res.end('403 not flie');                
				return;            
			}            
			// 遍历目录            
			fs.readFile("./template.html",(err,data)=>{                
				if(err){                    
					return res.end('404 not find')                
				}                
				let prevDisplay = "block";//上一级目录                
				if(url == '/'){                    
					prevDisplay = "none";                
				}                
				// 读取文件夹                
				fs.readdir(tmp,(err,files)=>{                    
					if(err){                        
						return res.end('Can not find dir');                    
					}                    
					let content = '';                    
					files.forEach((item)=>{                        
						let type = ""; //是文件还是文件夹                        
						let separate = ""; //文件夹后加/                        
						let stats2 = fs.statSync(tmp + item);//查看文件详细信息                        
						if(stats2.isDirectory()){                            
							type = "dir";                            
							separate = "/";                        
						}else{                            
							type = "file";                        
						}                        
						content += `                            
							<tr>                                
								<td>                                    
									<a class = "icon ${type}" href = "http://127.0.0.1:${config.port + url + item + separate}">${item + separate}</a>                                
								</td>                                
								<td>                                    
									${stats2.ctime.toLocaleDateString()}                                
								</td>                                
								<td>                                    
									${parseInt(stats2.size/1024)+1}KB                                
								</td>                            
							</tr>`                    		
					})                    
					// 替换                    
					data = data.toString();//转换为字符串                    
					data = data.replace("^_^",content);//文件                    
					data = data.replace(/{{path}}/g,url.substring(1));//当前文件夹                    
					data = data.replace('{{display}}',`style = "display: ${prevDisplay};"`);//上一级目录                    
					data = data.replace(/{{parentPath}}/g,url.substring(0,url.substr(url.length-1).lastIndexOf('/')+1));//上一级目录的跳转                    
					res.end(data);                
				})            
			})        
		}else{           
 			// 渲染文件            
 			fs.readFile(tmp,(err,data)=>{                
 				if(err){                    
 					res.end();                
 				}                
 			// 获取文件后缀名                
 			let ext = path.extname(tmp).substring(1);                
 			// 判断文件类型设置请求头                
 			if(ext in config.mineType.text){                   
  				res.setHeader('Content-Type',`${config.mineType.text[ext]};charset=${config.charset}`)                
  			}else if(ext in config.mineType.image){
  				res.setHeader('Content-Type',`${config.mineType.image[ext]}`)                
  			}else{                    
  				res.setHeader('Content-Type',`${config.mineType.other};charset=${config.charset}`)    
  			}                
  			res.end(data);            
		})        
  	}    
  }else{        
  	res.end('');   
  }
})

// 监听端口号
server.listen(config.port,()=>{    
	console.log('服务器启动成功');
})  

这里写的文件名只能为英文名
在这里插入图片描述

版权声明:本文为weixin_45846263原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_45846263/article/details/107302211