要提供静态文件(如images、CSS文件和JavaScript文件),请使用Express中的express.static
内置中间件功能,函数签名是:css
express.static(root, [options])
root
参数指定从中提供静态资源的根目录,有关options
参数的更多信息,请参阅express.static
。html
例如,使用如下代码在名为public
的目录中提供images、CSS文件和JavaScript文件:node
app.use(express.static('public'))
如今,你能够加载public
目录中的文件:express
http://localhost:3000/images/kitten.jpg http://localhost:3000/css/style.css http://localhost:3000/js/app.js http://localhost:3000/images/bg.png http://localhost:3000/hello.html
Express会查找相对于静态目录的文件,所以静态目录的名称不是URL的一部分。
要使用多个静态资源目录,请屡次调用express.static
中间件函数:segmentfault
app.use(express.static('public')) app.use(express.static('files'))
Express按照使用express.static
中间件函数设置静态目录的顺序查找文件。缓存
注意:为得到最佳结果,请使用反向代理缓存来提升服务静态资源的性能。
要为express.static
函数提供的文件建立虚拟路径前缀(文件系统中实际不存在路径),请为静态目录指定挂载路径,以下所示:安全
app.use('/static', express.static('public'))
如今,你能够从/static
路径前缀加载public
目录中的文件。app
http://localhost:3000/static/images/kitten.jpg http://localhost:3000/static/css/style.css http://localhost:3000/static/js/app.js http://localhost:3000/static/images/bg.png http://localhost:3000/static/hello.html
可是,你提供给express.static
函数的路径是相对于启动node进程的目录,若是从另外一个目录运行express应用程序,则使用要提供的目录的绝对路径更安全:函数
app.use('/static', express.static(path.join(__dirname, 'public')))
有关serve-static
函数及其选项的更多详细信息,请参阅serve-static
。性能