path模块+fs模块——实现HTML文件的拆分(JS+CSS+HTML)

 

 html模板:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>网页</title>
	<style>
		*{
			margin: 0;
			padding: 0;

		}

		#a1{
			width: 30%;
			height: 499px;
			float: left;
			background-color: red;
		}
		#a2{
			width: 40%;
		
			height: 400px;
			float: left;
			padding: 100px 0  0;
			background-color: red;


		}
		#a3{
			width: 30%;
			
			height: 499px;
			float: left;
			background: orange;
		
		}
		#a21{
			width: 100%;
			font-size: 40px;
			line-height: 200px;
			text-align: center;
			
			height: 200px;
			display: inline-block;
			background-color: yellow;

		}
		#a22{
			
			width: 100%;
			font-size: 40px;
			line-height: 200px;
			text-align: center;
		
			height: 200px;
			display: inline-block;
			background-color: orange;

		}
		body{
			text-align: center;

		}
		#a31{
			font-size: 70px;
			font-weight: bold;
			margin: 10px;

		}
	</style>
</head>
<body>
	<div id="a1">
		
	</div>
	<div id="a2">
		
		<h3 id="a21">
			09 : 07 : 89
		</h3>

		<h3 id="a22">
			06 : 06 : 86
		</h3>

	</div>

	<div id="a3">
		<button id="a31">改变样式的按钮</button>
	</div>

	<script>
		window.onload=function(){
			document.getElementById('a31').onclick=changestyle;
		}
		function changestyle(){
			var a3=document.getElementById("a3");
			var a2=document.getElementById("a2");
			var a1=document.getElementById("a1");
			a1.style.backgroundColor='black';
			a2.style.backgroundColor='pink';
			a3.style.backgroundColor='green';
		}
	</script>
</body>
</html>

创建两个正则表达式;分别匹配style和script

使用fs模块,读取需要处理的文件

自定义css方法:拆分css写入css文件

自定义js方法:拆分js写入js文件

自定义html方法:拆分html写入html文件

 使用 \ 转义字符使用\S表示非空白字符 ;*表示匹配任意次 \s表示空白字符----------------即正则

   [\s\S]*

// <style>............</style>----------------如何匹配style
// <script>............</script>---------------如何匹配script
const css=/<style>[\s\S]*<\/style>/
const js=/<script>[\S\s]*<\/script>/

使用文件模块 读取文件


const fs=require('fs');//使用require方法 导入文件系统
const path=require('path');//使用require方法 导入路径系统
fs.readFile(path.join(__dirname,"等待拆分的网页.html"),function(err,DateStr){
	if(err){
		console.log('文件读取失败'+err.message);

	}
	console.log('文件读取成功! 要开始拆分');

	Extractcss(DateStr);//拆分的函数
})

 开始进行拆分的函数————用到了exec函数进行字符串正则的提取  使用索引来拿+replace字符串的替换——替换两次--------------替换css部分

 


const fs=require('fs');//使用require方法 导入文件系统
const path=require('path');//使用require方法 导入路径系统


// <style>............</style>----------------如何匹配style
// <script>............</script>---------------如何匹配script
const css=/<style>[\s\S]*<\/style>/
const js=/<script>[\S\s]*<\/script>/

fs.readFile(path.join(__dirname,"等待拆分的网页.html"),function(err,DateStr){
	if(err){
		console.log('文件读取失败'+err.message);

	}
	console.log('文件读取成功! 要开始拆分');

	Extractcss(DateStr);
})
//exec() 方法用于检索字符串中的正则表达式的匹配。 有匹配的值返回该匹配值,否则返回 null。
//返回的结果是数组
//且数组的第一个值也就是索引为0 的值是所匹配的正则的内容
function Extractcss(Str){//提取css

	const c1=css.exec(Str);
	//console.log(c1.length);//测试代码
	c2=c1[0].replace('<style>','').replace('</style>','');//替换两次
	fs.writeFile(path.join(__dirname,'./css.css'),c2,'utf8',function(err){
 	if(err){
	 console.log('写入失败'+err.message);
 	}
	console.log("成功写入")
	})


}
function Extractcjs(){//提取js

}
function Extracthtml(){//提取html

}

  开始进行拆分的函数————用到了exec函数进行字符串正则的提取  使用索引来拿+replace字符串的替换——替换两次--------------替换js部分

function Extractcjs(Str){//提取js
	const j1=js.exec(Str);
	//console.log(c1.length);//测试代码
	j2=j1[0].replace('<script>','').replace('</script>','');//替换两次
	fs.writeFile(path.join(__dirname,'./js.js'),j2,'utf8',function(err){
 	if(err){
	 console.log('写入失败'+err.message);
 	}
	console.log("成功写入")
	})

}

  开始进行拆分完整的HTML代码————replace字符串的替换script-+style---变成link script——替换两次---------将那些内嵌的变成外嵌的----------使用正则匹配--两次replcae

 //因此在 Node.js中,定义了一个 Buffer 类,该类用来创建一个专门存放二进制数据的缓存区。

用到了buffer转字符串Str.toString();

function Extracthtml(Str){//提取html
	//因此在 Node.js中,定义了一个 Buffer 类,该类用来创建一个专门存放二进制数据的缓存区。
	var str=Str.toString();//将其用itf-8转换成字符串
	//console.log(str);//测试

	 const html=str.replace(css,'<link rel="stylesheet" href="./css.css">').replace(js,'<script src="./js.js" ></script>');

	fs.writeFile(path.join(__dirname,'./index.html'),html,'utf8',function(err){
 	if(err){
	 console.log('写入失败'+err.message);
 	}
	console.log("成功写入")
	})



}


全部代码


const fs=require('fs');//使用require方法 导入文件系统
const path=require('path');//使用require方法 导入路径系统


// <style>............</style>----------------如何匹配style
// <script>............</script>---------------如何匹配script
const css=/<style>[\s\S]*<\/style>/
const js=/<script>[\S\s]*<\/script>/

fs.readFile(path.join(__dirname,"等待拆分的网页.html"),function(err,DateStr){
	if(err){
		console.log('文件读取失败'+err.message);

	}
	console.log('文件读取成功! 要开始拆分');
	Extractcss(DateStr);
	Extractcjs(DateStr);
	Extracthtml(DateStr);
})
//exec() 方法用于检索字符串中的正则表达式的匹配。 有匹配的值返回该匹配值,否则返回 null。
//返回的结果是数组
//且数组的第一个值也就是索引为0 的值是所匹配的正则的内容
function Extractcss(Str){//提取css

	const c1=css.exec(Str);
	//console.log(c1.length);//测试代码
	c2=c1[0].replace('<style>','').replace('</style>','');//替换两次
	fs.writeFile(path.join(__dirname,'./css.css'),c2,'utf8',function(err){
 	if(err){
	 console.log('写入失败'+err.message);
 	}
	console.log("成功写入")
	})


}
function Extractcjs(Str){//提取js
	const j1=js.exec(Str);
	//console.log(c1.length);//测试代码
	j2=j1[0].replace('<script>','').replace('</script>','');//替换两次
	fs.writeFile(path.join(__dirname,'./js.js'),j2,'utf8',function(err){
 	if(err){
	 console.log('写入失败'+err.message);
 	}
	console.log("成功写入")
	})

}
function Extracthtml(Str){//提取html
	//因此在 Node.js中,定义了一个 Buffer 类,该类用来创建一个专门存放二进制数据的缓存区。
	var str=Str.toString();//将其用itf-8转换成字符串
	//console.log(str);//测试

	 const html=str.replace(css,'<link rel="stylesheet" href="./css.css">').replace(js,'<script src="./js.js" ></script>');

	fs.writeFile(path.join(__dirname,'./index.html'),html,'utf8',function(err){
 	if(err){
	 console.log('写入失败'+err.message);
 	}
	console.log("成功写入")
	})



}

执行 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
由于涉及到服务器文件的遍历,需要使用服务器端的代码。以下是使用Node.js实现服务器文件遍历的示例代码: ```javascript const fs = require('fs'); // 定义遍历函数 function traverseFolder(folderPath) { fs.readdir(folderPath, function(err, files) { if (err) { console.error(err); return; } files.forEach(function(file) { const fullPath = folderPath + '/' + file; fs.stat(fullPath, function(err, stats) { if (err) { console.error(err); return; } if (stats.isDirectory()) { // 如果是文件夹,递归进入 traverseFolder(fullPath); } else { // 如果是文件,可以做相应的处理 console.log(fullPath); } }); }); }); } // 调用遍历函数 traverseFolder('/path/to/your/folder'); ``` 上述代码中,`traverseFolder`函数用于遍历指定路径下的所有文件文件夹。对于每个文件夹,递归进入;对于每个文件,可以做相应的处理,例如打印路径。 此外,还需要在Node.js使用HTTP模块搭建一个简单的Web服务器,以便在浏览器中访问文件列表。以下是示例代码: ```javascript const http = require('http'); const fs = require('fs'); const path = require('path'); // 定义遍历函数 function traverseFolder(folderPath, callback) { fs.readdir(folderPath, function(err, files) { if (err) { callback(err); return; } const results = []; files.forEach(function(file) { const fullPath = folderPath + '/' + file; fs.stat(fullPath, function(err, stats) { if (err) { callback(err); return; } const item = { name: file, path: fullPath, isDirectory: stats.isDirectory() }; if (stats.isDirectory()) { // 如果是文件夹,递归进入 traverseFolder(fullPath, function(err, children) { if (err) { callback(err); return; } item.children = children; results.push(item); if (results.length === files.length) { callback(null, results); } }); } else { // 如果是文件,直接添加到结果数组中 results.push(item); if (results.length === files.length) { callback(null, results); } } }); }); }); } // 创建HTTP服务器 const server = http.createServer(function(req, res) { // 获取当前路径 const currentPath = '.' + req.url; // 如果是文件,直接返回文件内容 if (fs.existsSync(currentPath) && fs.statSync(currentPath).isFile()) { fs.readFile(currentPath, function(err, data) { if (err) { res.writeHead(500); res.end(); return; } res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(data); }); return; } // 如果是文件夹,返回文件列表 traverseFolder(currentPath, function(err, results) { if (err) { res.writeHead(500); res.end(); return; } // 生成HTML代码,展示文件列表 let html = '<ul>'; results.forEach(function(item) { html += '<li>'; if (item.isDirectory) { html += '<a href="' + item.path + '">' + item.name + '</a>'; if (item.children) { html += '<ul>'; item.children.forEach(function(child) { html += '<li><a href="' + child.path + '">' + child.name + '</a></li>'; }); html += '</ul>'; } } else { html += item.name; } html += '</li>'; }); html += '</ul>'; res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(html); }); }); // 启动服务器 server.listen(8080, function() { console.log('Server is listening on port 8080'); }); ``` 上述代码中,`traverseFolder`函数的作用与之前的示例代码相同,但这里将结果包装为一个对象数组,以便在浏览器中进行展示。同时,返回的结果是一个异步回调函数的参数,而非直接输出到控制台。 在HTTP服务器中,首先判断当前请求的路径是否是一个文件,如果是,则直接返回文件内容。否则,调用`traverseFolder`函数获取文件列表,并生成HTML代码,向浏览器输出。需要注意的是,这里使用了`fs.existsSync`和`fs.statSync`函数判断当前路径是否是一个文件,以避免遍历整个文件夹。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值