Node.js module-specific static resources

冷暖自知 提交于 2019-11-28 04:39:07

问题


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.


回答1:


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)



回答2:


Something like this should also work:

app.use(express.static(__dirname + '/public'));    
app.use('/mymodule', express.static(modulePath + '/public'));

See: http://groups.google.com/group/express-js/browse_thread/thread/c653fafc35fa85ed



来源:https://stackoverflow.com/questions/7746180/node-js-module-specific-static-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!