用node写个简单的静态服务器

直接上代码吧,我把它命名为 app.js, 只要在该文件所在目录下,控制台运行 node app.js 即可启动一个本地服务器了。

/**
 * 服务器
 * Author    jervy
 * Date     
 */

var MINE_TYPES = {
    'html':     'text/html',
    'xml':         'text/xml',
    'txt':         'text/plain',
    'css':         'text/css',
    'js':         'text/javascript',
    'json':     'application/json',
    'pdf':         'application/pdf',
    'swf':         'application/x-shockwave-flash',
    'svg':         'image/svg+xml',
    'tiff':     'image/tiff',
    'png':         'image/png',
    'gif':         'image/gif',
    'ico':         'image/x-icon',
    'jpg':         'image/jpeg',
    'jpeg':     'image/jpeg',
    'wav':         'audio/x-wav',
    'wma':         'audio/x-ms-wma',
    'wmv':         'video/x-ms-wmv',
    'woff2':     'application/font-woff2'
};
var PORT = 3000;
var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');
var root = process.cwd();

var server = http.createServer(function(request, response) {
    var pathname = decodeURIComponent(url.parse(request.url).pathname);
    var realPath = path.join(root, pathname);
    var ext = path.extname(realPath);
    if (!ext) {
        realPath = path.join(realPath, '/index.html');
        ext = '.html'
    }
    fs.exists(realPath, function(exists) {
        if (exists) {
            fs.readFile(realPath, 'binary', function(err, file) {
                if (!err) {
                    response.writeHead(200, {
                        'Content-Type': MINE_TYPES[ext.slice(1)] || 'text/plain'
                    });
                    response.write(file, 'binary');
                    response.end();
                } else {
                    response.writeHead(500, {
                        'Content-Type': 'text/plain'
                    });
                    response.write('ERROR, the reason of error is ' + err.code + '; Error number is ' + err.errno + '.');
                    response.end();
                }
            })
        } else {
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });
            response.write('This request URL ' + pathname + ' was not found on this server.');
            response.end();
        }
    });

});
server.listen(PORT);
console.log("server running at port " + PORT);

 

转载于:https://www.cnblogs.com/jervy/p/10008960.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值