nodejs 创建静态文件服务器

nodejs创建静态文件服务器

要说 NodeJS 的静态服务器,前辈们已有诸多实践,并都付之笔墨与大家共享,尝试列举如下:

 
/* Final Server */
 
var http = require('http'),
    fs = require('fs'),
    url = require('url'),   
    path = require('path'),
    mime = require('./mime');
     
     
http.createServer(function(request, response){
    //get path from request's url
    var pathname = url.parse(request.url).pathname;
    //map the path to server path
    var absPath = __dirname + "/webroot" + pathname;
     
    //test whether the file is exists first
    path.exists(absPath, function(exists) {
        if(exists) {
            //二进制方式读取文件
            fs.readFile(absPath,'binary',function(err, data) {
            //our work is here
            if(err) throw err;
             
            //获取合适的 MIME 类型并写入 response 头信息
            var ext = path.extname(pathname);
            ext = ext ? ext.slice(1) : 'unknown';
            console.log(ext);
            var contentType = mime.types[ext] || "text/plain";
            console.log(contentType);
            response.writeHead(200,{'Content-Type':contentType});
            //console.log(data);
            //使用二进制模式写
            response.write(data,'binary');
            response.end();
    });
        } else {
            //show 404
            response.end('404 File not found.');
        }
    });
}).listen(3000);
console.log('Server start at port 3000.');






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值