//创建网站服务器模板
const http = require('http');
const url = require('url');
//网站服务器对象
const app = http.createServer();
const path = require('path');
const fs = require('fs');
const mime = require('mime');
//客户端有请求
/* const querystring = require('querystring'); */
app.on('request', (req, res) => {//获取请求路径console.log(url.parse(req.url).pathname);let pathname = url.parse(req.url).pathname;pathname = pathname == '/' ? 'default.html' : pathname;//res.end(path.join(__dirname, pathname));let realPath = path.join(__dirname, pathname);let type = mime.getType(realPath);fs.readFile(realPath, (error, result) => {if (error != null) {res.writeHead(404, {'content-type': 'text/html;charset=utf8'})res.end('文件读取失败');return;}res.writeHead(200, {'content-type': type})res.end(result);})});
//监听端口
app.listen(3000);
console.log('服务器启动成功');
运行结果