res.sendFile()函數本質上在給定路徑上傳輸文件,並根據文件名擴展名設置Content-Type響應HTTP標頭字段。
用法:
res.sendFile(path [, options] [, fn])
參數:path參數描述路徑,而options參數包含各種屬性,例如maxAge,root等,而fn是回調函數。
返回:它重新調整對象。
快遞模塊的安裝:
- 您可以訪問安裝Express模塊的鏈接。您可以使用此命令安裝此軟件包。
npm install express
- 安裝Express模塊後,可以使用命令在命令提示符下檢查Express版本。
npm version express
- 之後,您可以僅創建一個文件夾並添加一個文件,例如index.js。要運行此文件,您需要運行以下命令。
node index.js
範例1: 文件名:index.js
var express = require('express');
var app = express();
var path = require('path');
var PORT = 3000;
// Without middleware
app.get('/', function(req, res){
var options = {
root:path.join(__dirname)
};
var fileName = 'Hello.txt';
res.sendFile(fileName, options, function (err) {
if (err) {
next(err);
} else {
console.log('Sent:', fileName);
}
});
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
現在,創建一個.txt文件,如下所示,我們在項目的根目錄中創建了Hello.txt文件,其內容如下:
Greetings from GeeksforGeeks
運行程序的步驟:
- 確保使用以下命令安裝了Express模塊:
npm install express
- 使用以下命令運行index.js文件:
node index.js
輸出:
Server listening on PORT 3000
- 現在打開瀏覽器並轉到http://localhost:3000 /,現在檢查控製台,您將看到以下輸出:
Server listening on PORT 3000 Sent:Hello.txt
在屏幕上,您將看到以下輸出:
Greetings from GeeksforGeeks
範例2: 文件名:index.js
var express = require('express');
const path = require('path');
var app = express();
var PORT = 3000;
// With middleware
app.use('/', function(req, res, next){
var options = {
root:path.join(__dirname)
};
var fileName = 'GeeksforGeeks.txt';
res.sendFile(fileName, options, function (err) {
if (err) {
next(err);
} else {
console.log('Sent:', fileName);
next();
}
});
});
app.get('/', function(req, res){
console.log("File Sent")
res.send();
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
確保您創建一個.txt文件,如此處所示,我們在項目的根目錄中使用以下文本創建了GeeksforGeeks.txt:
Welcome from GeeksforGeeks
使用以下命令運行index.js文件:
node index.js
現在打開瀏覽器並轉到http://localhost:3000 /,現在檢查控製台,您將看到以下輸出:
Server listening on PORT 3000 Sent:GeeksforGeeks.txt File Sent
您將在瀏覽器屏幕上看到以下輸出:
Welcome from GeeksforGeeks
參考: https://expressjs.com/en/5x/api.html#res.sendFile
相關用法
- p5.js nfs()用法及代碼示例
- PHP Ds\Map xor()用法及代碼示例
- p5.js nfp()用法及代碼示例
- d3.js d3.rgb()用法及代碼示例
- d3.js d3.map.set()用法及代碼示例
- p5.js nf()用法及代碼示例
- PHP each()用法及代碼示例
- p5.js nfc()用法及代碼示例
- PHP Ds\Set xor()用法及代碼示例
- PHP Ds\Map put()用法及代碼示例
- PHP max( )用法及代碼示例
- PHP ord()用法及代碼示例
- p5.js value()用法及代碼示例
注:本文由純淨天空篩選整理自gouravhammad大神的英文原創作品 Express.js res.sendFile() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。