node.js文件服务器

一个简单的node.js文件服务器

  • 启动文件app.js
//加载所需要的模块
var http = require('http');

var processRequest = require('./server');

//创建服务,这里很机智的把对response和request的处理封装成一个匿名函数,传入createServer中
//也可以直接在里面写,但是看起来不是很整洁
var httpServer = http.createServer((req, res) => {
    processRequest(req, res);
});

var port = 8888;

//指定一个监听的接口
httpServer.listen(port, function() {
    console.log(`app is running at port:${port}`);
});
  • http映射名
module.exports = {
    "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",
    'txt': 'text/plain',
    'md': 'text/plain',
    '': 'text/plain',
};
  • 核心服务类
var url = require('url');

var fs = require('fs');

var path = require('path');

var mime = require('./mime');

function processRequest(request, response) {


    //request里面切出标识符字符串
    var requestUrl = request.url;
    //url模块的parse方法 接受一个字符串,返回一个url对象,切出来路径
    var pathName = url.parse(requestUrl).pathname;

    //对路径解码,防止中文乱码
    var pathName = decodeURI(pathName);

    //解决301重定向问题,如果pathname没以/结尾,并且没有扩展名
    if (!pathName.endsWith('/') && path.extname(pathName) === '') {

        pathName += '/';
        var redirect = "http://" + request.headers.host + pathName;
        response.writeHead(301, {
            location: redirect
        });
        //response.end方法用来回应完成后关闭本次对话,也可以写入HTTP回应的具体内容。
        response.end();
    };

    //获取资源文件的绝对路径
    var filePath = path.resolve(__dirname + pathName);
    console.log(filePath);
    //获取对应文件的文档类型
    //我们通过path.extname来获取文件的后缀名。由于extname返回值包含”.”,所以通过slice方法来剔除掉”.”,
    //对于没有后缀名的文件,我们一律认为是unknown。
    var ext = path.extname(pathName);
    ext = ext ? ext.slice(1) : 'unknown';

    //未知的类型一律用"text/plain"类型
    var contentType = mime[ext] || "text/plain";

    fs.stat(filePath, (err, stats) => {
        if (err) {
            response.writeHead(404, { "content-type": "text/html" });
            response.end("<h1>404 Not Found</h1>");
        };
        //没出错 并且文件存在
        if (!err && stats.isFile()) {
            response.writeHead(200, { "content-type": contentType });
            //建立流对象,读文件
            var stream = fs.createReadStream(filePath);
            //错误处理
            stream.on('error', function() {
                response.writeHead(500, { "content-type": contentType });
                response.end("<h1>500 Server Error</h1>");
            });
            //读取文件
            stream.pipe(response,true);
        };
        //如果路径是目录
        if (!err && stats.isDirectory()) {
            var html = " <head><meta charset = 'utf-8'/></head>";
            //读取该路径下文件
            fs.readdir(filePath, (err, files) => {
                if (err) {
                    console.log("读取路径失败!");
                } else {
                    for (var file of files) {
                        if (file === "index.html") {
                            response.writeHead(200, { "content-type": "text/html" });
                            response.end(file);
                            break;
                        };
                        html += `<div><a href='${file}'>${file}</a></div>`;
                        console.log(html);
                    }
                    response.writeHead(200, { "content-type": "text/html" });
                    response.end(html);
                };
            });
        };
    });
};

module.exports = processRequest;
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,764评论 25 709
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,350评论 0 3
  • 人生最好的三种状态…… 不期而遇…… 不言而喻…… 不药而愈……
    温柔沉沦阅读 260评论 0 0
  • 每年会有一次畅游书海,与书为伴专题讲座。 亲我下午我们迎来了授课20年的任老师。任老师把诗人讲得栩栩如生。还时不时...
    2f03b45795d5阅读 160评论 0 0