|
|
@@ -0,0 +1,43 @@
|
|
|
+const http = require('http');
|
|
|
+const fs = require('fs');
|
|
|
+const path = require('path');
|
|
|
+
|
|
|
+const server = http.createServer((req, res) => {
|
|
|
+ let filePath = req.url === '/' ? '/index.html' : req.url;
|
|
|
+ filePath = path.join(__dirname, filePath);
|
|
|
+
|
|
|
+ const extname = path.extname(filePath);
|
|
|
+ let contentType = 'text/html';
|
|
|
+
|
|
|
+ switch (extname) {
|
|
|
+ case '.js':
|
|
|
+ contentType = 'text/javascript';
|
|
|
+ break;
|
|
|
+ case '.css':
|
|
|
+ contentType = 'text/css';
|
|
|
+ break;
|
|
|
+ case '.json':
|
|
|
+ contentType = 'application/json';
|
|
|
+ break;
|
|
|
+ }
|
|
|
+
|
|
|
+ fs.readFile(filePath, (err, content) => {
|
|
|
+ if (err) {
|
|
|
+ if (err.code === 'ENOENT') {
|
|
|
+ res.writeHead(404);
|
|
|
+ res.end('文件未找到');
|
|
|
+ } else {
|
|
|
+ res.writeHead(500);
|
|
|
+ res.end('服务器错误');
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ res.writeHead(200, { 'Content-Type': contentType });
|
|
|
+ res.end(content, 'utf-8');
|
|
|
+ }
|
|
|
+ });
|
|
|
+});
|
|
|
+
|
|
|
+const PORT = 8080;
|
|
|
+server.listen(PORT, () => {
|
|
|
+ console.log(`服务器运行在 http://localhost:${PORT}`);
|
|
|
+});
|