node实现简单的可以读取html页面的服务器
node.js实现简单的可以读取html页面的服务器
const http = require('http') const fs = require('fs') // 这个模块是第三方的,所以要命令行输入npm install mime 安装 // 使用这个模块要一个package.json文件,在命令行输入npm init -y 创建 const mime = require('mime') // 创建服务器 http.createServer( (request, response) => { // 获取文件的全路径 let filePath = __dirname + '/www' + request.url // 如果用户输入的是localhost:3000,也能进入首页 filePath = request.url === '/' ? filePath + 'index.html' : filePath // 获取MIME type let fileType = mime.getType(filePath) // 读取文件 fs.readFile(filePath, (error, result) => { // 如果error不是空,即读取失败 if(error != null){ // 服务器响应回去404,告诉用户找不页面 response.writeHead(404, { 'content-type': 'text/html;charset=utf8' }) response.end('<h2>文件读取失败</h2>') return } // 读取成功响应回去200 response.writeHead(200, { // 在浏览器读取html时会遇到css,js,jpg等文件,也会去请求这些文件 // 并响应回来,所以要动态的获取这些文件的类型 'content-type': fileType }) // 把读取文件的结果响应回去给用户 response.end(result) }) } ).listen(3000, error => { if(error != null){ console.log('服务器创建失败') console.log(error) }else{ console.log('服务器创建成功,监听端口为3000') console.log('访问地址:localhost:3000') } })
下面是我文件目录:

我的index.html代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>这是首页</h2> </body> </html>
运行结果如下:


浙公网安备 33010602011771号