12345678910111213141516171819202122232425262728293031323334 |
- import http from 'http';
- import url from 'url';
- import path from 'path';
- import fs from 'fs';
- import os from 'os';
- import mime from 'mime';
- import { fileURLToPath } from 'url';
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const app = http.createServer((req, res) => {
- let rootpath = __dirname;
- if (os.platform() === 'darwin' || os.platform() === 'linux')
- rootpath = path.join(process.env.HOME, './');
- let pathname = url.parse(req.url).pathname;
- pathname = pathname == '/' ? '/default.html' : pathname;
- let realPath = path.join(__dirname, 'public' + 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('文件读取失败');
- } else {
- res.writeHead(200, {
- 'content-type': type
- });
- res.end(result);
- };
- });
- });
- // 监听 3000 端口
- app.listen(3000);
- console.log('服务器已启动,监听 3000 端口,请访问 localhost:3000');
|