2017-06-20 125 views
0

我想在我的node.js服務器上簡單地提供靜態文件。如果url欄中的路徑鏈接到一個靜態文件,我可以輕鬆地做到這一點。然而,如果即時通訊嘗試列出目錄內容,我需要使用node.js文件系統調用。我可以列出目錄內容,但我想瀏覽每個級別並根據需要獲取內容。 類似於apache的默認功能如果目錄裏面沒有'index.html',它會列出所有的內容。如果在node.js中指定了目錄路徑,則列出目錄內容

apache list directory contents

如何使一個簡單的HTML頁面,列出目錄內容,可點擊瀏覽並服務?

具體而言,我有一個日誌文件夾,我想訪問。並在該文件夾內是子目錄,並分散各種日誌。

繼承人我到目前爲止所嘗試的。

//inside server.js 
// serve any static file inside my logs folder 
app.use('/logs', express.static('logs')); 

// routes.js 
var logger = require('../controllers/s3logs'); 

app.get('/listlogs', function (req, res) { 
     res.render('logpage', {logList : logger.findFiles()}); 
    }); 

// controller s3logs.js 
exports.findFiles = function(path) 
exports.findFiles = function (path) { 

if (path==undefined) 
{ 
    path='logs'; 
} 

var fileArray = fs.readdirSync(path); //get array of objects inside root dir 
var fileObjArray = []; 


// iterate through each file found in the directory 
// find stats, make an obj, and push to new array 

fileArray.forEach(function(item, index){ 
    const pathToItem = path+'/'+item ; 
    const stats = fs.statSync(pathToItem); 

    var fileObj = { 
     "name": item, 
     "path": pathToItem, 
     "isDir": stats.isDirectory(), 
     "size": stats.size, 
     "modified": stats.mtime 
    }; 

    fileObjArray.push(fileObj); 

    }); 

return fileObjArray; 
}; 

//logpage.html 
<body> 
<ul> 
    {% for file in loglist %} 
    <li {% if loop.first %} class="first"{% endif %}> 
     <a href= {{ file.path }}>{{ file.name }}</a> 
    </li> 
    {% endfor %} 
</ul> 
</body> 

此代碼工作,但我需要解決遍歷另一個目錄更深的路徑。再次呼叫我的功能。我可以通過一個帖子請求解決這個問題,但我覺得這已經變得太複雜了...... 有什麼建議嗎?

+0

你爲什麼試圖重新發明輪子? https://www.npmjs.com/package/express-directory –

+0

我最終使用了服務靜態中間件。它解決了我的問題。 –

回答

0

如果指定的路徑是目錄,則使用靜態中間件服務我自己的自定義html。

var serveStatic = require('serve-static'); 


// serve static logs files 
var serve = serveStatic('logs'); 

app.use('/logs', serve, function (req, res) { 
    // console.log(req) 
    res.render('logpage', {logList:s3logger.findFiles(req.originalUrl), currentPath: req.originalUrl}); 
});