69

我已经看到并使用了:

app.use("/css", express.static(__dirname + '/css'));

我不希望提供根目录中的所有文件,只提供一个文件“ipad.htm”。使用 express.js 以最少的代码量做到这一点的最佳方法是什么?

4

6 回答 6

120

res.sendFile(path_to_file);是你所需要的全部; 它将自动设置正确的标题并传输文件(它在内部使用与 相同的代码express.static)。

在小于 4 的 express 版本中,使用sendfile代替sendFile.

于 2012-07-13T22:01:25.343 回答
17
app.use("/css/myfile.css", express.static(__dirname + '/css/myfile.css'));
于 2013-07-07T03:06:25.800 回答
7

如果您只想提供单个静态文件,可以使用以下语法(基于原始问题的示例,根目录下的 ipad.htm):

app.use('/ipad.htm', express.static(__dirname, {index: 'ipad.htm'}));

express.static( dir )的默认行为是它会尝试从所需的dir发送一个“index.html”文件。index选项会覆盖此行为,并允许您选择预期的文件。

于 2020-01-06T16:31:41.133 回答
5

我发布了一个用于提供单个静态文件的小型库:https ://www.npmjs.com/package/connect-static-file

npm install connect-static-file

var staticFile = require('connect-static-file'); app.use('/ipad', staticFile(__dirname + '/ipad.html'));

与 express.static 的主要区别在于它不关心请求 url,如果路由匹配,它总是提供该文件。如果您将目录命名为“ipad.html”,它不会突然开始为整个目录提供服务。

于 2015-03-23T12:16:11.390 回答
0

基于 JoWie 的回答的快速示例:

npm 安装连接静态文件

npm 安装快递

var express = require('express');
var staticFile = require('connect-static-file');

var path = 'pathto/myfile.txt';
var options = {};
var uri = '/';
var app = express();
var port = 3000;

app.use(uri, staticFile(path, options));

app.listen(port, () => console.log(`Serving ${path} on localhost:${port}${uri}`));
于 2019-03-15T20:18:42.363 回答
-4
 fs.createReadStream(path).pipe(res);
于 2012-07-13T16:30:28.503 回答