HstarDoc icon indicating copy to clipboard operation
HstarDoc copied to clipboard

NodeJS:简单实现一个静态服务器

Open hstarorg opened this issue 6 years ago • 0 comments

const fs = require('fs');
const path = require('path');
const http = require('http');
const util = require('util');

const MIME_MAP = {
  '.js': 'text/javascript',
  '.css': 'text/css',
};

const WEB_ROOT = path.join(__dirname, 'webroot');

const server = http.createServer((req, res) => {
  const { url } = req;
  let fileUrl = '';
  if (/\.[a-zA-Z0-9]+$/.test(url)) {
    fileUrl = path.join(WEB_ROOT, url);
  } else {
    fileUrl = path.join(WEB_ROOT, 'index.html');
  }
  util
    .promisify(fs.exists)(fileUrl)
    .then(isExists => {
      if (!isExists) {
        res.write('404');
        return res.end();
      }
      const extName = path.extname(fileUrl);
      const mimeType = MIME_MAP[String(extName).toLowerCase()];
      if (mimeType) {
        res.writeHead(200, { 'content-type': mimeType });
      }
      fs.createReadStream(fileUrl).pipe(res);
    });
});

server
  .listen(80, () => {
    const addr = server.address();
    console.info('server started...', addr);
  })
  .on('error', console.error);

hstarorg avatar Aug 24 '19 06:08 hstarorg