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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| const http = require('http'); const path = require('path'); const fs = require('fs'); const mime = require('mime');
const server = http.createServer(); const baseURL = 'html';
function get(req, res) { const url = new URL(req.url, 'http://localhost'); const pathname = decodeURIComponent(url.pathname); const filepath = path.join(__dirname, baseURL, pathname); fs.stat(filepath, function (er, stat) { if (er) { if (er.code === 'ENOENT') { res.statusCode = 404; res.end('Not Found'); } else { res.statusCode = 500; res.end('Internal Server Error'); } } else { res.setHeader('Content-Type', mime.getType(filepath)); res.setHeader('Content-Length', stat.size); const stream = fs.createReadStream(filepath); stream.on('error', function () { res.statusCode = 500; res.end('Internal Server Error'); }); stream.pipe(res); } }); }
server.on('request', function (req, res) { switch (req.method) { case 'GET': get(req, res); break; case 'POST': break; default: break; } });
const hostname = process.argv[2] || '127.0.0.1'; const port = process.argv[3] || 3000;
server.listen({ hostname, port, });
console.log(`Server is running at http://${hostname}:${port}`);
|