Node.js模块特定的静态资源 [英] Node.js module-specific static resources

查看:159
本文介绍了Node.js模块特定的静态资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种优雅的方式将静态客户端文件资源(脚本,映像等)捆绑到Express模块​​中,并有系统地避免命名冲突?注册静态对象的模块特定实例很简单,如下所示:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆