如何使用node做一个简易web服务器。

前几天遇到一个需求写几个静态页面。但是页面要简单调几个接口  直接本地打开肯定是行不通啦。最简单的是装 apache 可以解决 但是这样的问题就是维护起来比较麻烦 于是有了这个方案 

首先上 package.json

{
  "name": "serve",
  "version": "1.0.0",
  "description": "",
  "main": "",
  "files": [
    "src",
    "dist/*.js"
  ],
  "scripts": {
    "dev": "node ./server/index.js"
  },
  "author": "zehui.zhang",
  "license": "MIT",
  "dependencies": {},
  "devDependencies": {
    "os": "^0.1.1"
  }
}

是不是很干净 没有任何第三方的包 接下来看下 server下的index(重点开始)

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

var rootPath = '.';

//mime 文件,用来做mine类型匹配的。网上能下载
var mineJSON = require('./mime.json');

var server = http.createServer(function (req, res) {

    var reqPath = url.parse(req.url, true).pathname;

    if (reqPath == '/favicon.ico') return;

    var extname = path.extname(reqPath);
    extname = extname.substr(1, extname.length - 1);

    var mineType = mineJSON[extname];

    if (reqPath == '/') reqPath = `/${config.defaultHtml || 'index'}.html`;

    var targetPath = rootPath + reqPath;

    console.log('targetPath: ' + targetPath);

    fs.readFile(targetPath, function (err, data) {
        if (err) {
            fs.readFile(rootPath + '/404.html', function (err, data) {
                if (err) {
                    res.writeHead(200, {'Context-Type': 'text/html;charset=UTF-8'});
                    res.end(new Buffer('<h1 style="text-align: center;">404 not found</h1>'));
                } else {
                    res.writeHead(200, {'Context-Type': 'text/html;charset=UTF-8'});
                    res.end(data);
                }
            });
        } else {
            res.writeHead(200, {'Content-Type': mineType + ';charset=UTF-8'});
            res.end(data);
        }

    });

});

server.listen(config.port, config.host);
console.log(`调试模式访问 http://${config.host}:${config.port} 配置默认html页面请到server/config.js中配置defaultHtml 默认加载index.html`);

config,js

const os = require('os');
///获取本机ip///
function getIPAdress() {
    var interfaces = os.networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }
}
const myHost = getIPAdress();
module.exports = {
    defaultHtml: 'index',
    host: myHost,
    port: 9000
};

mime.json

{
	"hqx":"application/mac-binhex40",
	"cpt":"application/mac-compactpro",
	"csv":["text/x-comma-separated-values", "text/comma-separated-values", "application/octet-stream", "application/vnd.ms-excel", "application/x-csv", "text/x-csv", "text/csv", "application/csv", "application/excel", "application/vnd.msexcel"],
	"bin":"application/macbinary",
	"dms":"application/octet-stream",
	"lha":"application/octet-stream",
	"lzh":"application/octet-stream",
	"exe":["application/octet-stream", "application/x-msdownload"],
	"class":"application/octet-stream",
	"psd":"application/x-photoshop",
	"so":"application/octet-stream",
	"sea":"application/octet-stream",
	"dll":"application/octet-stream",
	"oda":"application/oda",
	"pdf":["application/pdf", "application/x-download"],
	"ai":"application/postscript",
	"eps":"application/postscript",
	"ps":"application/postscript",
	"smi":"application/smil",
	"smil":"application/smil",
	"mif":"application/vnd.mif",
	"xls":["application/excel", "application/vnd.ms-excel", "application/msexcel"],
	"ppt":["application/powerpoint", "application/vnd.ms-powerpoint"],
	"wbxml":"application/wbxml",
	"wmlc":"application/wmlc",
	"dcr":"application/x-director",
	"dir":"application/x-director",
	"dxr":"application/x-director",
	"dvi":"application/x-dvi",
	"gtar":"application/x-gtar",
	"gz":"application/x-gzip",
	"php":"application/x-httpd-php",
	"php4":"application/x-httpd-php",
	"php3":"application/x-httpd-php",
	"phtml":"application/x-httpd-php",
	"phps":"application/x-httpd-php-source",
	"js":"application/x-javascript",
	"swf":"application/x-shockwave-flash",
	"sit":"application/x-stuffit",
	"tar":"application/x-tar",
	"tgz":["application/x-tar", "application/x-gzip-compressed"],
	"xhtml":"application/xhtml+xml",
	"xht":"application/xhtml+xml",
	"zip":["application/x-zip", "application/zip", "application/x-zip-compressed"],
	"mid":"audio/midi",
	"midi":"audio/midi",
	"mpga":"audio/mpeg",
	"mp2":"audio/mpeg",
	"mp3":["audio/mpeg", "audio/mpg", "audio/mpeg3", "audio/mp3"],
	"aif":"audio/x-aiff",
	"aiff":"audio/x-aiff",
	"aifc":"audio/x-aiff",
	"ram":"audio/x-pn-realaudio",
	"rm":"audio/x-pn-realaudio",
	"rpm":"audio/x-pn-realaudio-plugin",
	"ra":"audio/x-realaudio",
	"rv":"video/vnd.rn-realvideo",
	"wav":["audio/x-wav", "audio/wave", "audio/wav"],
	"bmp":["image/bmp", "image/x-windows-bmp"],
	"gif":"image/gif",
	"jpeg":["image/jpeg", "image/pjpeg"],
	"jpg":["image/jpeg", "image/pjpeg"],
	"jpe":["image/jpeg", "image/pjpeg"],
	"png":["image/png", "image/x-png"],
	"tiff":"image/tiff",
	"tif":"image/tiff",
	"css":"text/css",
	"html":"text/html",
	"htm":"text/html",
	"shtml":"text/html",
	"txt":"text/plain",
	"text":"text/plain",
	"log":["text/plain", "text/x-log"],
	"rtx":"text/richtext",
	"rtf":"text/rtf",
	"xml":"text/xml",
	"xsl":"text/xml",
	"mpeg":"video/mpeg",
	"mpg":"video/mpeg",
	"mpe":"video/mpeg",
	"qt":"video/quicktime",
	"mov":"video/quicktime",
	"avi":"video/x-msvideo",
	"movie":"video/x-sgi-movie",
	"doc":"application/msword",
	"docx":["application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/zip"],
	"xlsx":["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/zip"],
	"word":["application/msword", "application/octet-stream"],
	"xl":"application/excel",
	"eml":"message/rfc822",
	"json":["application/json", "text/json"]
}

最后启动 npm run dev 效果如下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值