nodejs 模板引擎

自制替换模板

template.js  

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


var server = http.createServer()
var wwwDir = 'D:/vuejs/nodejs/day2'

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

	fs.readFile('./template.html', function ( err, data ) {
		if (err) {
			return res.end('404 Not fount!!!!')
		}

		//1. 得到路径下所有文件名和目录名
			//fs.readdir('路径',function (err, data) {})
		//2. 将得到的文件名和目录名替换到template.html中
			//2.1 在template.html 中需要替换的位置预留特殊标记
			//2.2 根据 files 生成 Html 内容
		fs.readdir(wwwDir, function (error , files) {
			if (error) {
				return res.end('Can not find www dir.')
			}
			var content = ''
			files.forEach(function (item) {
				 content += `
				 	<tr>
						<td>${item}</td>
						<td>删 | 改</td>
					</tr>
				 `
			})
			data = data.toString()
			//console.log(data.replace( 'replacestring', content ));
			data = data.replace( 'replacestring', content )
			res.end( data )
		})

		
	})
})


server.listen(3000, function () {
	console.log('runing.....')
})

  

template.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>213</title>
</head>
<body>
	<table>
		<tr>
			<td>文件名</td>
			<td>操作</td>
		</tr>
		replacestring
	</table>
</body>
</html>

  

猜你喜欢

转载自www.cnblogs.com/jasonLiu2018/p/11184401.html