node.js启动文件服务器 并自动查询index.html等默认文件

 

'use strict';

const http = require('http'),
    fs = require('fs'),
    url = require('url'),
    path = require('path');

// 从命令行参数获取root目录,默认是当前目录
var root = path.resolve(process.argv[2] || '.');

console.log('Static root dir:' + root);

// 定义文件夹下的默认访问的文件
var defaultFiles = ['index','index.html','index.htm','index.php','default.html'];

// 创建服务器
var server = http.createServer(function(request,response){
    
    // 获得URL的path
    var pathname = url.parse(request.url).pathname;
    // 获得对应的本地文件路径
    var filepath = path.join(root,pathname);

    // 标记查找到第几个默认文件
    var defaultFileIndex = 0;
    // 查找默认文件
    const findDefaultFunc = function() {
        const p = path.join(filepath,defaultFiles[defaultFileIndex]);
        defaultFileIndex++ ;
        findFileFunc(p);
    }

    // 查找文件
    const findFileFunc = function(p){
        // 获取文件状态
        fs.stat(p,function(err,stats){
            if(!err && stats.isFile()){
                // 如果没有出错并且文件存在
                console.log('200 '+request.url);
                // 发送200响应
                response.writeHead(200);
                // 将文件流导向response
                fs.createReadStream(p).pipe(response);
            }else if(!err && defaultFileIndex ===0 && stats.isDirectory()){
                // 如果是第一次查找发现是文件夹,就去查找默认文件
                findDefaultFunc()
            }else if(defaultFileIndex > 0 && defaultFileIndex < defaultFiles.length){
                // 如果已经经历过查找默认文件的程序,但任然没找到,继续查找剩下定义的默认文件
                findDefaultFunc()
            }else{
                // 所有默认文件都查找过了,任然没找到
                console.log('404 ' + request.url);
                // 发送404响应
                response.writeHead(404);
                response.end('404 Not Found');
            }
        })
    }
    findFileFunc(filepath);
})

server.listen(8080);

console.log('Server is runing at http://127.0.0.1:8080/');

代码来源以下文章的评论区

https://www.liaoxuefeng.com/wiki/1022910821149312/1023025830950720

 

posted @ 2024-04-04 11:45  C羽言  阅读(25)  评论(0)    收藏  举报