node 环境下简单web服务器搭建代码

零、前置

  已经安装 node 环境。

一、代码片段

var http = require('http');
var path = require('path');
var fs = require('fs');
var url = require('url');

var server = http.createServer((req, res) => {
  var staticPath = path.join(__dirname, '');
  var pathObj = url.parse(req.url, true);

  if (pathObj.pathname == '/') pathObj.pathname += 'index.html';

  var filePath = path.join(staticPath, pathObj.pathname);

  // 异步读取文件数据
  fs.readFile(filePath, 'binary', (err, fileContent) => {
    if (err) {
      res.writeHead(404, 'Not Found');
      res.end('<h1>404 Not Found</h1>');
    } else {
      res.writeHead(200, 'ok');
      res.write(fileContent, 'binary');
      res.end();
    }
  })
})

server.listen(8012);
console.log('server is ok!')

二、优缺点

  缺点:1.暂不支持热更新;

     2.IE 下读取不了 css 文件的 MIME 类型(ie 出来走两步);

原文地址:https://www.cnblogs.com/cc-freiheit/p/12367196.html