这次给大家带来nodejs通过响应回写渲染页面步骤详解,nodejs通过响应回写渲染页面的注意事项有哪些,下面就是实战案例,一起来看一下。
我们一般通过node框架提供的api操作页面渲染,如何利用原始回写的方式来实现同样的功能呢
下面是通过node 提供的异步地读取一个文件的全部内容api readfile进行操作,代码如下:
html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="./static/style.css" rel="external nofollow" />
<title>document</title>
</head>
<body>
<p>这是一个p </p>
<p>这是一个p </p>
<p>这是一个p </p>
<p>这是一个p </p>
<p>这是一个p </p>
<p>这是一个p </p>
<p>这是一个p </p>
<p>这是一个p </p>
<p>这是一个p </p>
<p>这是一个p </p>
<p>这是一个p </p>
<script type="text/javascript" src="./static/test.js"></script>
</body>
</html>
/static 文件夹里面放test.js 和 style.css 文件
p:nth-child(1){
font-size: 50px;
color: red;
}
p:nth-child(3){
font-size: 80px;
color: blue;
}
p:nth-child(6){
font-size: 100px;
color: blueviolet;
}
app.js
// 搭建服务
var http = require('http');
var fs = require('fs');
var server = http.createserver();
server.on('listening',()=> {
console.log('server starts at localhost 8080');
})
server.listen('8080','localhost');
//监听服务
server.on('request',(req,res)=>{
if(req.url == '/') {//渲染html文件
fs.readfile('./html/node.html',(err,info)=>{
res.write(info);
res.end();
})
} else if(req.url.startswith('/static')) {//统一渲染html需要的static静态文件到页面
fs.readfile(dirname + req.url,(err,info) =>{
res.write(info);
res.end();
})
}
})
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
angular2模块与共享模块使用方法
怎样获得number类型数组中最大元素
以上就是nodejs通过响应回写渲染页面步骤详解的详细内容。