静态服务器
代码
const http = require(‘http‘) const chalk = require(‘chalk‘) const conf = require(‘./config/default‘) const path = require(‘path‘) const fs = require(‘fs‘) const server = http.createServer((req, res) => { const url = req.url const filePath = path.join(conf.root, url) console.log(filePath) fs.stat(filePath, (err, stats) => { if (err) { res.statusCode = 404 res.setHeader(‘Content-Type‘,‘text/plain‘) res.end(`${filePath}is not a directory or file`) } if (stats.isFile()) { res.statusCode = 200 res.setHeader(‘Content-Type‘,‘text/plain‘) fs.createReadStream(filePath).pipe(res) } else if (stats.isDirectory()) { fs.readdir(filePath, (err, files) => { res.statusCode = 200 res.setHeader(‘Content-Type‘, ‘text/plain‘) res.end(files.join(‘,‘)) }) } }) // res.statusCode = 200 // res.setHeader(‘Content-Type‘,‘text/plain‘) // res.end(‘Hello World‘) }) server.listen(conf.port, conf.hostname, () => { const address = `http://${conf.hostname}:${conf.port}` console.info(`Server run at ${chalk.green(address)}`) })
我们能在页面查看项目文件
原文:https://www.cnblogs.com/sonwrain/p/10629576.html