preview.js 1.08 KB
const http = require('http');
const fs = require('fs');
const path = require('path');

const ROOT = path.resolve(__dirname);

const server = http.createServer((req, res) => {
  let filePath = path.join(ROOT, req.url === '/' ? '/examples/abort-demo.html' : req.url);
  const extname = String(path.extname(filePath)).toLowerCase();
  const mimeTypes = {
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.css': 'text/css',
    '.json': 'application/json',
    '.svg': 'image/svg+xml'
  };
  const contentType = mimeTypes[extname] || 'application/octet-stream';

  fs.readFile(filePath, (error, content) => {
    if (error) {
      res.writeHead(404, { 'Content-Type': 'text/html' });
      res.end('<h1>404 Not Found</h1>');
    } else {
      res.writeHead(200, {
        'Content-Type': contentType,
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': '0'
      });
      res.end(content);
    }
  });
});

const PORT = 8081;
server.listen(PORT, () => {
  console.log(`Preview at http://localhost:${PORT}/examples/abort-demo.html`);
});