Js-提供单个静态文件最简单的方法是什么?

我已经看到并利用了:

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

我不希望服务根目录中的所有文件,只有一个文件‘ ipad.htm’。使用 Express.js 以最少的代码量完成这项工作的最佳方法是什么?

37344 次浏览
 fs.createReadStream(path).pipe(res);

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

在小于4的快速版本中,使用 sendfile而不是 sendFile

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

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

npm install connect-static-file

Var staticFile = demand (‘ connect-static-file’) ; Use (’/ipad’,staticFile (_ _ dirname +’/ipad.html’) ;

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

基于 JoWie 的回答,举个简单的例子:

Npm install connect-static-file

安装快递

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}`));

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

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

Static (导演)的默认行为是尝试从所需的 导演发送一个‘ index.html’文件。索引选项覆盖了这种行为,允许您选择预期的文件。