1)引入fs模块
const fs=require(‘fs’)
2)fs.readFile() 读取html文件
3)输出html页面
res.end(data)
const http = require('http') //引用系统提供的http
const fs = require('fs') //引入fs模块
const config = require('./config').config // 引用config文件
const server = http.createServer((req, res) => { //http模块的一个方法,实例化一个服务
fs.readFile(__dirname + '/index.html', 'utf-8', function (err, data) { //读取html文件
if (err) {
res.statusCode = 404 // 执行成功状态码
res.setHeader('Content-Type', 'text/plain')//http传输协议
res.end('Not Found')
} else {
res.statusCode = 200 // 执行成功状态码
res.setHeader('Content-Type', 'text/html')//http传输协议
res.end(data) //输出html页面
}
})
})
//运行服务器
server.listen(config.port, config.hostname, () => {
console.log(`Server running at http://${config.hostname}:${config.port}`)// 在控制台打印
})