node搭建简单静态服务器,返回html页面

44 阅读1分钟

有时候需要制作静态页面,希望公司其他同学能够实时访问,又不想引入其他库,http-serve之类的多个页面也很麻烦…

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

http
  .createServer(function (request, response) {
    if (request.url === '/') {
      response.writeHead(200, { 'Content-Type': 'text/plain' });
      response.end('Hello World\n');
    } else if (request.url === '/agreement') {
      fs.readFile('./src/agreement/index.html', function (err, data) {
        if (err) {
          throw err;
        } else {
          response.end(data);
        }
      });
    } else if (request.url === '/privacy') {
      fs.readFile('./src/privacy/index.html', function (err, data) {
        if (err) {
          throw err;
        } else {
          response.end(data);
        }
      });
    } else {
        response.writeHead(200, { 'Content-Type': 'text/plain' });
        response.end('Hello World\n');
    }
  })
  .listen(8888, function () {
    console.log('OK,访问:localhost:8888');
  });