1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
const http = require('http') const fs = require('fs') const mime = require('mime') const url = require('url') const path = require('path') const [hostname, port] = ['127.0.0.1', 3000] const server = http.createServer((req, res)=>{ let pathname = decodeURIComponent(path.join(__dirname,url.parse(req.url).pathname)) if(fs.statSync(pathname).isDirectory()){ res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'}) fs.readdir(pathname,(err,files)=>{ res.write('<ul>') files.forEach(element => { let link = path.join(url.parse(req.url).pathname,element) res.write(`<li><a href = "${link}">${element}</a></li>`) }); res.end('<ul>') }) } else{ fs.readFile(pathname, 'binary', (err, data)=>{ if(err){ res.writeHead(500,{'Content-Type':'text/plain'}) res.end(JSON.stringify(err)) return false } res.writeHead(200,{'Content-Type':`${mime.lookup(pathname)};charset:utf-8`}) res.write(data,'binary') res.end() }) } res.statusCode = 200 }) server.listen(port, hostname,()=>{ console.log(`服务器运行在 http://${hostname}:${port}`) }) |