nodejs轻量服务器后端

搭建思路

server.js主函数 + mine.js配置文件 + index.html 测试网页

server.js文件

var PORT = 8080;       //端口
var DIR = 'test1';     //用于存放html的目录

var http = require('http');
var url=require('url');
var fs=require('fs');
var mine=require('./mine').types;
var path=require('path');

var server = http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    var realPath = path.join(DIR, pathname);
    //console.log(realPath);
    var ext = path.extname(realPath);

    ext = ext ? ext.slice(1) : 'unknown';
    fs.exists(realPath, function (exists) {
       if (!exists) {
           response.writeHead(404, {
               'Content-Type': 'text/plain'
           });
           response.write("This request URL " + pathname + " was not found on this server.");
           response.end();
       } else {
           fs.readFile(realPath, "binary", function (err, file) {
               if (err) {
                   response.writeHead(500, {
                       'Content-Type': 'text/plain'
                   });
                   response.end(err);
               } else {
                   var contentType = mine[ext] || "text/plain";
                   response.writeHead(200, {
                       'Content-Type': contentType
                   });
                   response.write(file, "binary");
                   response.end();
               }
           });
       }
   });
});

server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");

mine.js

exports.types = {
   "css": "text/css",
   "gif": "image/gif",
   "html": "text/html",
   "ico": "image/x-icon",
   "jpeg": "image/jpeg",
   "jpg": "image/jpeg",
   "js": "text/javascript",
   "json": "application/json",
   "pdf": "application/pdf",
   "png": "image/png",
   "svg": "image/svg+xml",
   "swf": "application/x-shockwave-flash",
   "tiff": "image/tiff",
   "txt": "text/plain",
      "wav": "audio/x-wav",
   "wma": "audio/x-ms-wma",
   "wmv": "video/x-ms-wmv",
   "xml": "text/xml"
}

测试网页自备index.html

<h1>hello world</h1>

执行脚本

node server.js
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: NodeJS服务器