2017-04-25 101 views
1

我想從兩個目錄中使用快遞提供靜態文件。表達多個靜態路由正則表達式解析

我從兩個目錄服務的原因是由於命名文件之間的衝突在目錄#1被服務具有目錄#2

在目錄#1匹配的目錄名稱,它僅包含的文件:

/path/to/dir1/foo    (where 'foo' is a file) 

在目錄#2,它將包含包含文件的子目錄:

/path/to/dir2/foo/bar   (where 'foo' is a dir && 'bar' is a file) 

我的目標是能夠執行後續荷蘭國際集團的命令:

wget "http://myserver:9006/foo" 
wget "http://myserver:9006/foo/bar" 

下面的代碼片段將完成一切,直到目錄#2對我來說:

​​

我試圖用一個正則表達式添加第二個靜態路由,看是否有'/',這樣我可以將它指向目錄#2。我想沿着這些線路的東西,但都沒有成功:

app.use('/[^/]*([/].*)?', express.static('/path/to/dir2/')); 

app.use('/.*/.*', express.static('/path/to/dir2/')); 

我希望得到任何幫助。

在此先感謝!

回答

1

根據the docs,您可以多次撥打express.static,它會按您指定的目錄順序搜索文件。

文件夾結構:

/ 
    static/ 
    s1/ 
     foo # Contents: s1/foo the file 
    s2/ 
     foo/ 
     bar # Contents: s2/foo/bar the file. 

該應用程序是除了兩個靜態行你確切的代碼:

const express = require('express') 
const app = express() 

app.use('/', express.static('static/s1')) 
app.use('/', express.static('static/s2')) 

const server = app.listen(9006,() => { 
    let host = server.address().address 
    let port = server.address().port 

    console.log(`Example app listening at http://${host}:${port}`) 
}) 

並且頁面按預期

$ curl localhost:9006/foo 
s1/foo the file 

$ curl localhost:9006/foo/bar 
s2/foo/bar the file. 
+0

工作就像一個魅力!非常感謝! – jlents