當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js ServerHttp2Stream http2stream.respondWithFile(path[, headers[, options]])用法及代碼示例

http2stream.respondWithFile(path[, headers[, options]])

曆史
版本變化
v14.5.0、v12.19.0

允許明確設置日期標題。

v10.0.0

現在支持任何可讀文件,不一定是常規文件。

v8.4.0

添加於:v8.4.0


參數

發送一個常規文件作為響應。 path 必須指定常規文件,否則將在 Http2Stream 對象上發出 'error' 事件。

使用時,Http2Stream對象的Duplex接口會自動關閉。

可以指定可選的 options.statCheck 函數,以使用戶代碼有機會根據給定文件的 fs.Stat 詳細信息設置其他內容標頭:

如果在嘗試讀取文件數據時發生錯誤,將使用標準 INTERNAL_ERROR 代碼使用 RST_STREAM 幀關閉 Http2Stream。如果定義了onError 回調,那麽它將被調用。否則流將被銷毀。

使用文件路徑的示例:

const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
  function statCheck(stat, headers) {
    headers['last-modified'] = stat.mtime.toUTCString();
  }

  function onError(err) {
    // stream.respond() can throw if the stream has been destroyed by
    // the other side.
    try {
      if (err.code === 'ENOENT') {
        stream.respond({ ':status': 404 });
      } else {
        stream.respond({ ':status': 500 });
      }
    } catch (err) {
      // Perform actual error handling.
      console.log(err);
    }
    stream.end();
  }

  stream.respondWithFile('/some/file',
                         { 'content-type': 'text/plain; charset=utf-8' },
                         { statCheck, onError });
});

options.statCheck 函數也可用於通過返回 false 來取消發送操作。例如,條件請求可以檢查統計結果以確定文件是否已被修改以返回適當的 304 響應:

const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
  function statCheck(stat, headers) {
    // Check the stat here...
    stream.respond({ ':status': 304 });
    return false; // Cancel the send operation
  }
  stream.respondWithFile('/some/file',
                         { 'content-type': 'text/plain; charset=utf-8' },
                         { statCheck });
});

content-length 標頭字段將被自動設置。

offsetlength 選項可用於將響應限製為特定範圍子集。例如,這可以用於支持 HTTP Range 請求。

options.onError 函數還可用於處理在啟動文件交付之前可能發生的所有錯誤。默認行為是銷毀流。

當設置options.waitForTrailers 選項時,將在排隊要發送的最後一塊有效負載數據後立即發出'wantTrailers' 事件。然後可以使用http2stream.sendTrailers() 方法將尾隨標頭字段發送到對等方。

當設置options.waitForTrailers 時,在傳輸最後一個DATA 幀時,Http2Stream 不會自動關閉。用戶代碼必須調用 http2stream.sendTrailers()http2stream.close() 來關閉 Http2Stream

const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
  stream.respondWithFile('/some/file',
                         { 'content-type': 'text/plain; charset=utf-8' },
                         { waitForTrailers: true });
  stream.on('wantTrailers', () => {
    stream.sendTrailers({ ABC: 'some value to send' });
  });
});

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 http2stream.respondWithFile(path[, headers[, options]])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。