Pure JavaScript HTTP Parser

0.5.10 · active · verified Sun Apr 19

http-parser-js is a JavaScript implementation of an HTTP protocol parser, designed to replace Node.js's internal C-based `http_parser.c` module. Its primary differentiator is its flexibility and tolerance for malformed or non-standard HTTP data, making it suitable for interacting with legacy services that do not strictly adhere to HTTP parsing rules, unlike Node.js's default stricter parser. The package is currently at version 0.5.10. It does not follow a strict release cadence but updates as needed for compatibility or bug fixes. While originally created to mitigate V8's C++ function call overhead, its current main benefit lies in its error tolerance. It can be used both as a monkey-patch replacement for Node.js's internal parser or as a standalone component for parsing raw HTTP buffers.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to monkey-patch Node.js's internal HTTP parser with `http-parser-js` before initializing the native `http` module, then starts a basic HTTP server.

import { HTTPParser } from 'http-parser-js';
import http from 'http';

// Monkey patch before you require http for the first time.
// Note: This specific usage pattern primarily targets CommonJS environments in Node.js.
// For ESM, you might need a different approach or a build step to ensure `require` behavior.
if (typeof process.binding === 'function' && process.binding('http_parser')) {
  process.binding('http_parser').HTTPParser = HTTPParser; // Assuming HTTPParser is already imported
  console.log('http-parser-js successfully monkey-patched into Node.js runtime.');
}

// Now, `http` module will use http-parser-js
const server = http.createServer((req, res) => {
  console.log(`Received request for: ${req.url}`);
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello from http-parser-js powered server!\n');
});

server.listen(3000, () => {
  console.log('Server running on port 3000');
});

// Example of making a request to demonstrate it's working
// setTimeout(() => {
//   http.get('http://localhost:3000/', (res) => {
//     let data = '';
//     res.on('data', (chunk) => { data += chunk; });
//     res.on('end', () => { console.log('Client received:', data); server.close(); });
//   }).on('error', (err) => {
//     console.error('Client error:', err.message);
//     server.close();
//   });
// }, 1000);

view raw JSON →