[譯]當 Node.js Core 遇到 HTTP/2

gongpeione發表於2019-02-16

原文:Say hello to HTTP/2 for Node.js Core

第一次嘗試翻譯文章,如果有翻譯的不好或者有錯誤的地方還望大佬們指點一二,謝謝。

幾分鐘前我開啟了一個 pull-request,它為 Nodejs Core 提供了初始的 HTTP/2 實現。雖然還不堪用,但對 Node.js 來說是一個重要的里程碑。

因為這只是一個pull-request,你要想和它愉快的玩耍的話需要做好下面這些準備工作。

首先你需要跟著這個介紹來配置好 Node.js 的構建環境。

然後切換到 initial-pr 分支:

$ git clone https://github.com/jasnell/node
$ git checkout initial-pr

然後開始構建:

$ ./configure
$ make -j8

構建需要小一會兒時間,你可以先去覓個食等待構建完畢。

構建完成之後,隨手幾行程式碼就可以開一個 HTTP/2 的服務了:

const http2 = require(`http2`);
const server = http2.createServer();
server.on(`stream`, (stream, requestHeaders) => {
  stream.respond({ `:status`: 200, `content-type`: `text/plain` });
  stream.write(`hello `);
  stream.end(`world`);
});
server.listen(8000);

由於現在這個 HTTP/2 還處在實驗階段,所以你在執行上面程式碼的時候需要加上一個 --expose-http2 引數:

$ node --expose-http2 h2server.js

需要注意的是,上面啟動的服務是一個明文 TCP 連線,而瀏覽器對於使用 HTTP/2 協議的要求是必須使用 TLS。然而我們可以開一個簡單的 HTTP/2 客戶端來達到目的:

const http2 = require(`http2`);
const client = http2.connect(`http://localhost:8000`);
const req = client.request({ `:method`: `GET`, `:path`: `/` });
req.on(`response`, (responseHeaders) => {
  // do something with the headers
});
req.on(`data`, (chunk) => {
  // do something with the data
});
req.on(`end`, () => client.destroy());

設定好一個開啟 TLS 的 HTTP/2 服務只需要額外的幾個步驟:

const http2 = require(`http2`);
const options = {
  key: getKeySomehow(),
  cert: getCertSomehow()
};
const server = http2.createSecureServer(options);
server.on(`stream`, (stream, requestHeaders) => {
  stream.respond();
  stream.end(`secured hello world!`);
});
server.listen(43);

你可以到 文件 中獲取更多有關 tls.createServer() 引數裡的 keycert 的使用說明。

儘管現在還有很多的細節需要處理,還有很多的問題需要修復,但是這個最初的實現已經提供了足夠多的功能了,包括:

  1. 支援推流(Push Stream)

  2. respondWithFile() 和 respondWithFD() 可以高效的繞過 Stream API 傳送原始檔案資料

  3. 支援 TLS 和 明文連線

  4. 完全支援多路複用的流(stream multiplexing)

  5. 支援 HTTP/2 的優先順序(Prioritization)和流量控制(Flow Control)

  6. 支援 HTTP/2 Trailer 頭

  7. 支援 HPACK 頭壓縮

  8. 儘可能接近當前 HTTP/1 API 的 API 相容層

開發將會繼續進行,例如安全性加強、效能優化和 API 優化。我們付出的越多,Node.js 就會變的越好。

祝大家複用愉快。

相關文章