Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
hstarorg opened this issue Aug 24, 2019 · 0 comments
Open

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

hstarorg opened this issue Aug 24, 2019 · 0 comments

Comments

@hstarorg
Copy link
Owner

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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant