标签:span text adf lse name dex listen javascrip creates
1、新建一个server.js文件
var http = require(‘http‘); //用来启服务 var fs = require(‘fs‘); //用来读取文件 var root = __dirname //你本地放index.html页面的文件路径 console.log(root) //开启服务 var server = http.createServer(function(req, res) { var url = req.url; console.log(url) var file = root + url; redfile(file, req, res) }).listen(8088); //端口号 function redfile(url, req, res) { let contentType = ‘text/html;charset="utf-8"‘ if (/\.html$/.test(url)) { contentType = ‘text/html;charset="utf-8"‘ } else if (/\.css$/.test(url)) { contentType = ‘text/css; charset=utf-8‘ } else if (/\.js$/.test(url)) { contentType = ‘application/javascript; charset=utf-8‘ } else if (/\.jpg$/.test(url)) { contentType = ‘image/jpg‘ } else if (/\.png$/.test(url)) { contentType = ‘image/png‘ } else if (/\.ico$/.test(url)) { contentType = ‘image/png‘ } fs.readFile(url, function(err, data) { if (err) { res.writeHeader(404, { ‘content-type‘: ‘text/html;charset="utf-8"‘ }); res.write(‘<h1>404错误</h1><p>你要找的页面不存在</p>‘); res.end(); } else { res.writeHeader(200, { ‘content-type‘: contentType }); res.write(data); //将index.html显示在客户端 res.end(); } }) } console.log(‘8088端口服务器开启成功‘);
2、再终端运行该文件
node server.js
3、浏览器打开index.html页面
http://localhost:8088/index.html
注意自己目录,这里我server.js 和 index.html是同级的
标签:span text adf lse name dex listen javascrip creates
原文地址:https://www.cnblogs.com/xiaohuizhang/p/12187029.html