Node.js HTTP2 Complete Reference Last Updated : 23 Feb, 2023 Comments Improve Suggest changes Like Article Like Report HTTP2 module is used to provide an implementation of the HTTP2 protocol. It reduces overheads by compressing the server request headers. Example: JavaScript // Node.js program to demonstrate the // close event method const http2 = require('http2'); const fs = require('fs'); // Private key and public certificate for access const options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'), }; // Creating and initializing server // by using http2.createServer() method const server = http2.createServer(options); server.on('stream', (stream, requestHeaders) => { stream.respond({ ':status': 200, 'content-type': 'text/plain' }); stream.write('hello '); // Getting session object // by using session method const http2session = stream.session; // Getting alpnProtocol of this session // by using alpnProtocol method const alpnProtocol = http2session.alpnProtocol; stream.end("session protocol : " + alpnProtocol); http2session.close(); // Handling 'close' event http2session.on('close',() => { console.log("session is closed"); }) // Stopping the server // by using the close() method server.close(() => { console.log("server destroyed"); }) }); server.listen(8000); // Creating and initializing client // by using tls.connect() method const client = http2.connect( 'http://localhost:8000'); const req = client.request({ ':method': 'GET', ':path': '/' }); req.on('response', (responseHeaders) => { console.log("status : " + responseHeaders[":status"]); }); req.on('data', (data) => { console.log('Received: %s ', data.toString().replace(/(\n)/gm,"")); }); req.on('end', () => { client.close(() => { console.log("client destroyed"); }) }); Output: status : 200 Received: hello Received: local window size : 65535 client localSettings server localSettings The Complete List of HTTP2 module are listed below: Class: Http2Session Class: Http2Session Event Description timeout There is no activity on the Http2Session after the configured number of milliseconds.NCloseThe ‘close’ Event in the http2 server is emitted when the Http2Session has been destroyed.Class: Http2Session Methods Description state()Return miscellaneous information about the current state of the Http2Session.socket()It is an inbuilt application programming interface of class http2sessionremoteSettings()Get a prototype-less object describing the current remote settings of this Http2Session.destroyed()Check if the session is destroyed or not.type()Return the type of session instance used in the peerencrypted()Check if the Http2Session is connected with a TLSSocket or not.localSettings()Get the prototype-less object describing the current local settings of this Http2Session.pendingSettingsAck()Indicate whether the Http2Session is currently waiting for an acknowledgment of a sent SETTINGS frame.close()close this particular session.closed()Check if this Http2Session instance has been closed or not.alpnProtocol()Get the alp protocol property associated with this http2session object.unref()Return instance of the socket object associated with this session object.destroy()Destroy this particular session.connecting()Check if this Http2Session instance is still connecting or not.ping()Sends a PING frame to the connected HTTP/2 peer.setTimeout()Set the duration for a time after which a particular action will take place. Class: ClientHttp2Session Class: ClientHttp2Session Methods Description request()Return the object of ClientHttp2Stream. Class: Http2Stream Class: Http2Stream Event Description TimeoutThere is no activity on the Http2Stream after the configured number of milliseconds. closeThe ‘close’ Event in http2 server is emitted when the Http2Stream has been destroyed.Class: Http2Stream Methods Description state()Get miscellaneous information about the current state of the Http2Stream.priority()Update the priority for this Http2Stream instance.setTimeout()Set the duration for a time after which a particular action will take place.id()Return numeric stream identifier of this Http2Stream.closed()Return true if the stream is closed other wise false.endAfterHeaders()Return true if END_STREAM flag was set in the request or response HEADERS frame received.pending()Check if Http2Stream instance has been assigned a numeric stream identifier or not.destroyed()Return true if the stream is destroyed otherwise false.session()Get a reference to the Http2Session instance that owns this Http2Stream.close()Close the Http2Stream instance.rstCode()Set to the RST_STREAM error code reported when the Http2Stream is destroyed.sentHeaders()Get the object containing the outbound headers sent to this Http2Stream.sentInfoHeaders()Get the object containing the outbound headers sent to this Http2Stream. Class: ServerHttp2Stream Class: ServerHttp2Stream Method Description additionalHeaders()Send an additional informational HEADERS frame to the connected HTTP/2 peer.headersSent()Check if the header were sent or not.pushAllowed()Check if the header were sent or notrespond()This is used to sent the response header of the particular stream to its client. Class: http2.Http2ServerRequest Class: http2.Http2ServerRequest Properties Description aborted Check if the particular server request is aborted or not.Class: http2.Http2ServerRequest Event Description close The ‘close’ Event in the http2 server is emitted when an underlying Http2Stream was closed.Class: http2.Http2ServerRequest Method Description url()Get the Request URL string. This contains only the URL that is present in the actual HTTP request.httpVersion()Get the HTTP version either associated with server or client.headers()Get the request/response headers object.rawHeaders()Get the raw request/response headers to list exactly as they were received.destroy()This is used to destroy the request.authority()Get the string representation of the request authority pseudo-header field.complete()Check whether this request has been completed, aborted, or destroyed or not.method()Get the string representation of the request .scheme()Get the request scheme pseudo-header field indicating the scheme portion of the target URL..rawTrailers()Get the raw request/response trailer keys and values exactly as they were received.socket()Get a Proxy object that acts as a net.Socket (or tls.TLSSocket). Class: http2.Http2ServerResponse Class: http2.Http2ServerResponse Properties Description headersSent Check if headers were sent or not.Class: http2.Http2ServerResponse Event Description close The ‘close’ Event in the http2 server is emitted when an underlying Http2Stream was closed.finishThe ‘finish’ event in the http2 server is emitted when the last segment of the response headers and body have been sent.Class: http2.Http2ServerResponse Method Description setHeader()Set the header name and the particular value of that data header.setTimeout()Set the duration for a time after which a particular action will take place.stream()Get the object of HTTP stream backing this response.statusMessage()Return an empty string because it is not supported by HTTP/2 (RFC 7540 8.1.2.4).writableEnded()Check if the response.end() has been called or not.write()Send the chunk of the response body to the client.writeHead()Send the response header to the request.sendDate()Check if the Date header is automatically generated and sent in the response or not.socket()Get a Proxy object that acts as a net.Socket.statusCode()Show the different status of data header during the transaction.getHeaderNames()Return an array containing the unique names of the current outgoing headers.removeHeader()Remove a header that has been queued for implicit sending.hasHeader()Check if the header identified by name is currently set in the outgoing headers or not.getHeaders()Return a shallow copy of the current outgoing headers.end()Send the signal that all the response header and body have been sent.finished()Check whether the response has completed or not.getHeader()Read out a header that has already been queued but not sent to the client. http2.constants: http2.constants Properties Description constants Provide the error codes for particular errors. http2 Methods: http2 Methods Description getPackedSettings()Provide an object containing the serialized representation of the given HTTP/2connect()Return a ClientHttp2Session instance.getUnpackedSettings()Provide an HTTP/2 Settings Object containing the deserialized settingsgetDefaultSettings()Provide an object containing the default settings for an Http2Session instance.createServer()Create a net.Server object.prompt.get()This function is used for I/O operations.aborted()Check if ‘aborted’ event is emitted or not.bufferSize()Get the number of characters currently buffered to be written. Comment More infoAdvertise with us Next Article Node.js HTTP2 Complete Reference kartik Follow Improve Article Tags : JavaScript Web Technologies Node.js Node.js-HTTP2 Similar Reads Node.js Tutorial Node.js is a powerful, open-source, and cross-platform JavaScript runtime environment built on Chrome's V8 engine. It allows you to run JavaScript code outside the browser, making it ideal for building scalable server-side and networking applications.JavaScript was earlier mainly used for frontend d 4 min read Node.js BasicNodeJS IntroductionNodeJS is a runtime environment for executing JavaScript outside the browser, built on the V8 JavaScript engine. It enables server-side development, supports asynchronous, event-driven programming, and efficiently handles scalable network applications. NodeJS is single-threaded, utilizing an event l 5 min read How to Install Node.js on LinuxInstalling Node.js on a Linux-based operating system can vary slightly depending on your distribution. This guide will walk you through various methods to install Node.js and npm (Node Package Manager) on Linux, whether using Ubuntu, Debian, or other distributions.PrerequisitesA Linux System: such a 6 min read How to Install Node.js on WindowsInstalling Node.js on Windows is a straightforward process, but it's essential to follow the right steps to ensure smooth setup and proper functioning of Node Package Manager (NPM), which is crucial for managing dependencies and packages. This guide will walk you through the official site, NVM, Wind 6 min read NodeJS BasicsNodeJS is a powerful and efficient open-source runtime environment built on Chrome's V8 JavaScript engine. It allows developers to run JavaScript on the server side, which helps in the creation of scalable and high-performance web applications. In this article, we will discuss the NodeJs Basics and 7 min read Node First ApplicationNodeJS is widely used for building scalable and high-performance applications, particularly for server-side development. It is commonly employed for web servers, APIs, real-time applications, and microservices.Perfect for handling concurrent requests due to its non-blocking I/O model.Used in buildin 4 min read NodeJS REPL (READ, EVAL, PRINT, LOOP)NodeJS REPL (Read-Eval-Print Loop) is an interactive shell that allows you to execute JavaScript code line-by-line and see immediate results. This tool is extremely useful for quick testing, debugging, and learning, providing a sandbox where you can experiment with JavaScript code in a NodeJS enviro 5 min read NodeJS NPMNPM (Node Package Manager) is a package manager for NodeJS modules. It helps developers manage project dependencies, scripts, and third-party libraries. By installing NodeJS on your system, NPM is automatically installed, and ready to use.It is primarily used to manage packages or modulesâthese are 6 min read NodeJS Global ObjectsIn NodeJS global objects are the objects that are accessible in the application from anywhere without explicitly using the import or require. In browser-based JavaScript, the window object is the global scope, meaning it holds all global variables and functions. In NodeJS, instead of the window obje 6 min read NodeJS ModulesIn NodeJS, modules play an important role in organizing, structuring, and reusing code efficiently. A module is a self-contained block of code that can be exported and imported into different parts of an application. This modular approach helps developers manage large projects, making them more scal 6 min read Node.js Local ModuleA local module in Node.js refers to a custom module created in an application. Unlike the built in or third-party modules, local modules are specific to the project and are used to organize and reuse your code across different parts of your application.Local Module in Node.jsLocal modules in Node.js 2 min read Node.js Assert ModuleNode.js Assert ModuleAssert module in Node.js provides a bunch of facilities that are useful for the assertion of the function. The assert module provides a set of assertion functions for verifying invariants. If the condition is true it will output nothing else an assertion error is given by the console.Assert Module i 3 min read Node.js assert() FunctionThe assert() function in Node.js is used for testing and verifying assumptions in your code. It is part of the built-in assert module, which provides a set of assertion functions to perform various checks and validations.Node assert FunctionIn assert() function, if the value is not truth, then a Ass 3 min read Node.js assert.deepStrictEqual() FunctionThe assert module provides a set of assertion functions for verifying invariants. The assert.deepStrictEqual() function tests for deep equality between the actual and expected parameters. If the condition is true it will not produce an output else an assertion error is raised. Syntax: assert.deepStr 2 min read Node.js assert.doesNotThrow() FunctionThe assert module provides a set of assertion functions for verifying invariants. The assert.doesNotThrow() function asserts that the function fn does not throw an error. Syntax: assert.doesNotThrow(fn[, error][, message]) Parameters: This function accepts the following parameters as mentioned above 3 min read Node.js assert.equal() FunctionThe assert module provides a set of assertion functions for verifying invariants. The assert.equal() function tests for equality between the actual and the expected parameters. If the condition is true it will not produce an output else an assertion error is raised. Syntax: assert.equal(actual, exp 2 min read Node.js assert.ifError() FunctionThe assert module provides a set of assertion functions for verifying invariants. The assert.ifError() function throws value if value is not undefined or null. When testing the error argument in callbacks, this function is very useful.Syntax:  assert.ifError(value) value: This parameter holds the ac 2 min read Node.js assert.match() FunctionThe assert module provides a set of assertion functions for verifying invariants. The assert.match() function expects the string input to match the regular expression. If the condition is true it will not produce an output else an assertion error is raised. Syntax: assert.match(string, regexp[, mes 2 min read Node.js assert.notDeepEqual() FunctionThe assert module provides a set of assertion functions for verifying invariants. The assert.notDeepEqual() function tests deep strict inequality between the actual and the expected parameters. If the condition is true it will not produce an output else an assertion error is raised.Syntax: assert.no 2 min read Node.js Assert Complete ReferenceAssert module in Node.js provides a bunch of facilities that are useful for the assertion of the function. The assert module provides a set of assertion functions for verifying invariants. If the condition is true it will output nothing else an assertion error is given by the console. Example: JavaS 2 min read Node.js Buffer ModuleNode.js BuffersNode.js Buffers are used to handle binary data directly in memory. They provide a way to work with raw binary data streams efficiently, crucial for I/O operations, such as reading from files or receiving data over a network.Buffers in Node.jsBuffers are instances of the Buffer class in Node.js. Buff 4 min read Node.js Buffer.copy() MethodBuffer is a temporary memory storage that stores the data when it is being moved from one place to another. It is like an array of integers. The Buffer.copy() method simply copies all the values from the input buffer to another buffer. Syntax:buffer.copy( target, targetStart, sourceStart, sourceEnd 2 min read Node.js Buffer.includes() MethodBuffer is a temporary memory storage which stores the data when it is being moved from one place to another. It is like an array of integers. The Buffer.includes() method checks whether the provided value is present or included in the buffer or not. Syntax:buffer.includes( value, byteOffset, encodin 2 min read Node.js Buffer.compare() MethodBuffer is a temporary memory storage that stores the data when it is being moved from one place to another. It is like an array of integers. Buffer.compare() method compares the two given buffers. Syntax: buffer1.compare( targetBuffer, targetStart, targetEnd, sourceStart, sourceEnd ) Parameters: Th 3 min read Node.js Buffer.alloc() MethodThe Buffer.alloc() method is used to create a new buffer object of the specified size. This method is slower than Buffer.allocUnsafe() method but it assures that the newly created Buffer instances will never contain old information or data that is potentially sensitive. Syntax Buffer.alloc(size, fil 2 min read Node.js Buffer.equals() MethodThe Buffer.equals() method is used to compare two buffer objects and returns True of both buffer objects are the same otherwise returns False. Syntax: buffer.equals( buf ) Parameters: This method accepts single parameter otherBuffer which holds the another buffer to compare with buffer object. Retur 1 min read Node.js Buffer.subarray() MethodThe buffer.subarray() method is an inbuilt application programming interface of the buffer module which is used to crop a part of array i.e. create sub-array from an array.Syntax:  Buffer.subarray( starting_index, ending_index ) Parameters: This method has two parameters as mentioned above and desc 3 min read Node.js Buffer.readIntBE() MethodThe Buffer.readIntBE() method is used to read the number of bytes for a buffer at a given offset and interprets the result as a two's complement signed value. Syntax: buffer.readIntBE( offset, byteLen ) Parameters: This method accepts two parameters as mentioned above and described below: offset: It 2 min read Node.js Buffer.write() MethodThe Buffer.write() method writes the specified string into a buffer, at the specified position. If buffer did not contain enough space to fit the entire string, only part of string will be written. However, partially encoded characters will not be written. Syntax: buffer.write( string, offset, lengt 2 min read Node.js Buffer Complete ReferenceBuffers are instances of the Buffer class in Node.js. Buffers are designed to handle binary raw data. Buffers allocate raw memory outside the V8 heap. Buffer class is a global class so it can be used without importing the Buffer module in an application. Example: JavaScript --> We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Got It ! Improvement Suggest changes Suggest Changes Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal. Create Improvement Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all. Suggest Changes min 4 words, max Words Limit:1000 Thank You! Your suggestions are valuable to us. '); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append(''); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `${editorValue}`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('.suggest-bottom-btn').css("display","none"); $('#suggestion-section-textarea').hide() $('.thank-you-message').css('display', 'flex'); $('.suggestion-section').css('display', 'none'); jQuery('#suggestion-modal-alert').hide(); }, error:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 4 Words and Maximum Words limit is 1000."); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append(''); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append(''); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });