简体   繁体   English

如何使用node.js实现虚拟目录并表达?

[英]How can I implement virtual directories with node.js and express?

I want to use the express static server configuration for implementing an static server: 我想使用快速静态服务器配置来实现静态服务器:

app.configure(function() {
    app.use(express.static(__dirname + '/public'));
});

But I want to map the URL http://myhost/url1 to directory C:\\dirA\\dirB and http://myhost/url2 to directory C:\\dirC 但是我想将URL http://myhost/url1到目录C:\\dirA\\dirB ,将http://myhost/url2到目录C:\\dirC

How can it be implemented using express.static? 如何使用express.static实现它?

This should work for you: 这应该为您工作:

var serveStatic = require( "serve-static" );
app.use('/url1', serveStatic('c:\\dirA\\dirB'));
app.use('/url2', serveStatic('C:\\dirC'));

Take a look at the documentation for app.use() . 看看app.use()的文档。

Depending on how many directories you're planning to map this way, you could simply make symlinks for those directories in your public folder. 根据多少目录你打算这样地图,你可以简单地做在你的那些目录符号链接public文件夹。

In Windows: 在Windows中:

mklink /D c:\dirA\dirB public\url1

In Linux or OSX: 在Linux或OSX中:

ln -s /dirA/dirB public/url1

Then your static assets server should serve from those directories transparently (I've never tested on Windows but I don't see why it wouldn't work). 然后,您的静态资产服务器应该透明地从这些目录中提供服务(我从未在Windows上进行过测试,但是我看不出为什么它不起作用)。

Alternatively, if you wanted to include some kind of dynamic routing, you could write your own middleware to replace express.static which is actually connect.static under the hood. 另外,如果您想包含某种动态路由,则可以编写自己的中间件来替换express.static ,该中间件实际上是在connect.static Take a look at static.js in the connect source and see how it's implemented, it should be fairly straightforward to write your own variation. 看一下连接源中的static.js并查看其实现方式,编写自己的变体应该很简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM