原生node
const http = require('http')
const url = require('url')
const fs = require('fs')
const path = require('path')
const mime = require('mime')
const server = http.createServer()
server.on('request', (req, res) => {
let pathname = url.parse(req.url).pathname;
pathname = pathname == '/' ? '/index.html' : pathname
const type = mime.getType(pathname)
if (pathname && pathname !== '/favicon.ico') {
fs.readFile(path.join(__dirname, `public${pathname}`), (error, data) => {
if (error != null) {
res.writeHead(404, {
'content-type': 'text/html;charset=utf8'
})
res.end('找不到文件404')
} else {
res.writeHead(200, {
'content-type': type
})
res.end(data)
}
})
}
})
server.listen(3000);
express
const express = require('express')
const app = express()
const path = require('path')
app.use(express.static(path.join(__dirname, './public')))
app.listen(3000, () => {
console.log('running')
})