使用underscore模块的template功能实现对HTML的数据注入
代码是:npm i underscore
server.js文件
var http = require('http');
const fs = require('fs');
var _ = require("underscore");
var server = http.createServer();
server.on('request', function (req, res) {
var music = {
Id: 1002,
title: '梦里水乡',
singer: '老八秘制小汉堡',
type: '奥利给'
}
const url = req.url;
if (url === '/show') {
fs.readFile(__dirname + url + '.html', 'utf-8', function (err, data) {
if (err) {
res.end(err.message);
} else {
var compiled = _.template(data);
var htmlstr = compiled(music);
res.end(htmlstr);
}
})
} else {
res.end('404 not found!!!!!!');
}
});
server.listen(3000, "127.0.0.1", function () {
console.log("server is listening 127.0.0.1:3000");
});
show.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>歌单</title>
</head>
<body>
<ul>
<li>歌曲信息: <%=Id%>
</li>
<li>歌曲名称:<%=title%>
</li>
<li>歌手:<%=singer%>
</li>
</ul>
</body>
</html>
显示效果
|