Search code examples
node.jshttp2

NodeJS native http2 support


Does NodeJS 4.x or 5.x natively support the HTTP/2 protocol? I know there's http2 package but it's an external thing.

Are there some plans to merge http2 support into the Node's core?


Solution

  • --expose-http2 flag enables experimental HTTP2 support. This flag can be used in nightly build (Node v8.4.0) since Aug 5, 2017 (pull request).

    node --expose-http2 client.js
    

    client.js

    const http2 = require('http2');
    const client = http2.connect('https://stackoverflow.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 flag also can be added since Node v8.5.0.

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

    client.mjs

    import http2 from 'http2';
    
    const client = http2.connect('https://stackoverflow.com');
    

    I use NVS (Node Version Switcher) for testing nightly builds.

    nvs add nightly
    nvs use nightly