表示多个静态路由正则表达式解析

时间:2017-04-25 13:18:46

标签: node.js regex express

我正在尝试使用express来从两个目录中提供静态文件。

我在两个目录中提供服务的原因是由于在目录#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:

"use strict";
const express = require('express');
const app     = express();

app.use('/',    express.static('/path/to/dir1/'))

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

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

我正在尝试使用正则表达式添加第二个静态路由,以查看路由中是否有“/”,以便我可以将其指向目录#2。我正在考虑这些问题,但没有取得任何成功:

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

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

我将不胜感激。

提前致谢!

1 个答案:

答案 0 :(得分: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.
相关问题