node搭建本地服务器

 

 

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

http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname
  if (pathname == '/') pathname = '/index.html' var realPath = path.join(__dirname, pathname) console.log(realPath, '====pathRoute=======') fs.exists(realPath, function (exists) { if (!exists) { response.writeHead(404, { 'Content-Type': 'text/plain' }) response.end(); } else { fs.readFile(realPath, "binary", function (err, file) { if (err) { response.writeHead(500, { 'Content-Type': 'text/plain' }) response.end(err) } else { response.writeHead(200, { 'Content-Type': mime.getType(realPath) + ';charset="utf-8"' }) // response.setHeader('Content-Type', mime.getType(realPath)) response.write(file, "binary") response.end() } }); } }); }).listen(8888, () => { console.log("Server runing at port: http://localhost:8888 "); })

  

posted @ 2020-09-18 18:37  霜~  阅读(179)  评论(0编辑  收藏  举报