NodeJS 原生 http2 支持

NodeJS native http2 support

NodeJS 4.x 或 5.x 是否原生支持 HTTP/2 协议?我知道有 http2 包,但它是外部的东西。

是否有计划将 http2 支持合并到 Node 的核心中?

不,还没有。

这里是关于向核心 NodeJS 添加 HTTP/2 支持的讨论:https://github.com/nodejs/NG/issues/8

--expose-http2 标志启用实验性 HTTP2 支持。自 2017 年 8 月 5 日 (pull request) 起,此标志可用于夜间构建 (Node v8.4.0)。

node --expose-http2 client.js

client.js

const http2 = require('http2');
const client = http2.connect('https://whosebug.com');

const req = client.request();
req.setEncoding('utf8');

req.on('response', (headers, flags) => {
  console.log(headers);
});

let data = '';
req.on('data', (d) => data += d);
req.on('end', () => client.destroy());
req.end();

--experimental-modules 从 Node v8.5.0 开始也可以添加标志。

node --expose-http2 --experimental-modules client.mjs

client.mjs

import http2 from 'http2';

const client = http2.connect('https://whosebug.com');

我使用 NVS(节点版本切换器)来测试夜间构建。

nvs add nightly
nvs use nightly

Node 8.4.0 有一个实验性的 Http2 API。此处的文档 nodejs http2

从节点 v8.8.1 开始,当您是 运行 您的代码时,您不需要 --expose-http2 标志。

开始使用 HTTP/2 的最简单方法是利用 Node.js 公开的兼容性 API。

const http2 = require('http2');
const fs = require('fs');

const options = {
    key: fs.readFileSync('./selfsigned.key'),
    cert: fs.readFileSync('./selfsigned.crt'),
    allowHTTP1: true
}

const server = http2.createSecureServer(options, (req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.end('ok');
});

server.listen(443);

我已经写了更多关于使用 native HTTP/2 Node.js exposes to create a server here 的文章。