2015-04-12 128 views
0

我是新來的node.js,我試圖使用serveStatic函數來定位特定的文件。serveStatic()無法找到文件

當我在參數中指定確切的路徑時,它不起作用。但是,它僅適用於僅指定目錄的情況,並將該文件命名爲該目錄內的文件index.html。

關於如何使用它來查找特定文件的任何想法?任何幫助將非常感謝你們,謝謝!

下面是我的代碼

var connect = require('connect'), 
     http = require('http'), 
     serveStatic = require('serve-static'); 




    var app = connect(); 


    // app.use(serveStatic('public')); Works 


    app.use(serveStatic('public/test.html'));// doesn't work 
    app.use(function(req, res){ 


    }); 

    http.createServer(app).listen(3000); 
+0

您不清楚您要做什麼。你如何期待'app.use(serveStatic('public/test.html'));'工作? –

+0

你想要提供一個文件(只有一個文件,沒有更多)? –

+0

@LeonidBeschastny我試圖讓該文件作爲響應。它只是一個單一的文件。 – json2021

回答

0

serve-static是爲了服務於整個目錄(包括所有子目錄,如果有的話)。你不能用它來提供一個單一的文件。

你可以用serve-static做的是set a default file to be sent when user requests a root of your directory(默認情況下它是一個index.html文件):

app.use(serveStatic('public', {index: 'test.html'})); 

但如果你真的想送一個單一的文件,則最好使用this answer

app.use(function(req, res) { 
    res.sendfile('test.html', { 
    root: __dirname + '/public/' 
    }); 
}); 

儘管最好的解決方案是讀取一次該文件並緩存它。在這種情況下,每次有人請求該文件時,都不需要訪問存儲設備:

var html_data = require('fs').readFileSync('./public/test.html'); 

app.use(function(req, res) { 
    res.send(html_data); 
}); 
+0

@LenoidBeschastny。啊。我現在知道了。非常感謝你的明確表達。 – json2021