Node.js模块特定的静态资源 [英] Node.js module-specific static resources
问题描述
app.use(express.static(modulePath +'/ public'));
app.use(express.static(__ dirname +'/ public'));
但是如果这两个目录都包含一个styles.css文件,那么似乎是模块将覆盖应用程序。模块公共中的一个子目录可以用来避免这个问题,但是我真正想要的是将模块的资源映射到任意路径,以便
http:// localhost:3000 / mymodule / styles.css => < modulePath> /public/styles.css
http:// localhost:3000 / styles.css => < appPath> /public/styles.css
有没有办法这样做?我已经用编码技巧来做,所以我真的在寻找推荐的方式来完成它。另外,如果我缺少一些使这完全不必要的关键概念,我也想了解一下。
您可以创建一个 connect.static
的另一个实例,并在路由中使用它:
//新的静态中间件
var myModuleStatic = express.static(__ dirname +'/ mymodule')
// catch all子目录请求
app.get('/ mymodule / *',function(req,res){
//从url中删除subdir(静态从根服务)
req.url = req.url.replace(/ ^ \ / mymodule /,'')
//调用实际的中间件,捕获传递(未找到)
myModuleStatic(req,res,function(){
res.send(404)
})
})
app.listen(5555)
Is there an elegant way to bundle static client-side file resources (scripts,images,etc) into an Express module and systematically avoid naming conflicts? It's easy enough to register a module-specific instance of the static object like so:
app.use(express.static(modulePath + '/public'));
app.use(express.static(__dirname + '/public'));
but if both directories contain a "styles.css" file, it would seem that the one from the module will eclipse the one for the application. A subdirectory within the module's public could be used to avoid this problem, but what I really want is a way to map the module's resources to an arbitrary path such that
http://localhost:3000/mymodule/styles.css => <modulePath>/public/styles.css
http://localhost:3000/styles.css => <appPath>/public/styles.css
Is there already a way to do this? I've already done it with coding tricks, so I'm really looking for the recommended way to get it done. Also, if I'm missing some key concept that makes this totally unnecessary, I would like to learn about that too.
You can create another instance of connect.static
and use it within a route:
app = express.createServer()
app.configure(function(){
app.use(express.static(__dirname+'/public'))
})
// new static middleware
var myModuleStatic = express.static(__dirname+'/mymodule')
// catch all sub-directory requests
app.get('/mymodule/*', function(req, res){
// remove subdir from url (static serves from root)
req.url = req.url.replace(/^\/mymodule/, '')
// call the actual middleware, catch pass-through (not found)
myModuleStatic(req, res, function(){
res.send(404)
})
})
app.listen(5555)
这篇关于Node.js模块特定的静态资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!