在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 如何讓nodejs自動尋找目錄下index.html,default.html

如何讓nodejs自動尋找目錄下index.html,default.html

加載模塊

var
    fs = require('fs'),
    http = require('http'),
    path = require('path');

創(chuàng)建服務器,并請求和響應

var server = http.createServer(function(request, response) {
    var pathname = path.join(__dirname, request.url);
    console.log(pathname);
    // 獲取文件狀態(tài)
    fileState(pathname, function(res) {
        if (res) {
            //如果是一個文件,發(fā)送200響應
            response.writeHead(200);
            // 將文件流導向res
            fs.createReadStream(pathname).pipe(response);
        } else {
            // 當是一個目錄的時候如何讓程序自動尋找index.html default.html(問題在這里?)
        }
    })
}).listen(3000, function(err) {
    if (!err) console.log('服務器啟動成功');
})

獲取文件狀態(tài)的函數(shù)

function fileState(path, callback) {
    fs.stat(path, function(err, stats) {
        // 判斷是否是文件
        if (err) {
            return false;
        }
        callback(stats.isFile());
    })
}
回答
編輯回答
久愛她
fileState(pathname, function(res) {
        if (res) {
            //如果是一個文件,發(fā)送200響應
            response.writeHead(200);
            // 將文件流導向res
            fs.createReadStream(pathname).pipe(response);
        } else {
            // 當是一個目錄的時候如何讓程序自動尋找index.html default.html(問題在這里?)
            response.writeHead(200);
            // 將文件流導向res
            fs.createReadStream(pathname+'/index.html').pipe(response);
            
        }
    })
2017年12月8日 11:10