### Install fast-content-type-parse Source: https://github.com/fastify/fast-content-type-parse/blob/main/README.md Install the package using npm. ```sh npm install fast-content-type-parse ``` -------------------------------- ### Import fast-content-type-parse Source: https://github.com/fastify/fast-content-type-parse/blob/main/README.md Import the library in your JavaScript project. ```javascript const fastContentTypeParse = require('fast-content-type-parse') ``` -------------------------------- ### Benchmark Results Source: https://github.com/fastify/fast-content-type-parse/blob/main/README.md Performance comparison of fast-content-type-parse against other libraries for parsing Content-Type headers. ```sh node benchmarks/index.js util#MIMEType x 1,206,781 ops/sec ±0.22% (96 runs sampled) fast-content-type-parse#parse x 3,752,236 ops/sec ±0.42% (96 runs sampled) fast-content-type-parse#safeParse x 3,675,645 ops/sec ±1.09% (94 runs sampled) content-type#parse x 1,452,582 ops/sec ±0.37% (95 runs sampled) busboy#parseContentType x 924,306 ops/sec ±0.43% (94 runs sampled) Fastest is fast-content-type-parse#parse ``` -------------------------------- ### TypeScript Usage for Content-Type Parsing Source: https://context7.com/fastify/fast-content-type-parse/llms.txt Demonstrates how to import and use the `parse`, `safeParse`, and `defaultContentType` functions with TypeScript type annotations. ```typescript import fastContentTypeParse = require('fast-content-type-parse') const { parse, safeParse, defaultContentType } = fastContentTypeParse const ct: fastContentTypeParse.ContentType = parse('text/plain; charset=utf-8') // ct.type => string // ct.parameters => Record ``` -------------------------------- ### `parse(header)` — strict Content-Type header parser Source: https://context7.com/fastify/fast-content-type-parse/llms.txt Parses a `Content-Type` header string and returns an object with `type` (lowercased media type string) and `parameters` (null-prototype object of lowercased parameter names to their string values). Throws a `TypeError` with a descriptive message if the header is missing, not a string, contains an invalid media type, or has malformed parameters. Use this variant when the input is expected to always be valid and you want failures to surface loudly. ```APIDOC ## `parse(header)` — strict Content-Type header parser ### Description Parses a `Content-Type` header string and returns an object with `type` (lowercased media type string) and `parameters` (null-prototype object of lowercased parameter names to their string values). Throws a `TypeError` with a descriptive message if the header is missing, not a string, contains an invalid media type, or has malformed parameters. Use this variant when the input is expected to always be valid and you want failures to surface loudly. ### Method ```javascript const { parse } = require('fast-content-type-parse') // --- Basic media type --- const ct1 = parse('text/html') // => { type: 'text/html', parameters: {} } // --- With charset parameter --- const ct2 = parse('application/json; charset=utf-8') // => { type: 'application/json', parameters: { charset: 'utf-8' } } // --- Multiple parameters --- const ct3 = parse('multipart/form-data; boundary=----WebKitFormBoundary; charset=utf-8') // => { type: 'multipart/form-data', parameters: { boundary: '----WebKitFormBoundary', charset: 'utf-8' } } // --- Case normalization: type and parameter names are lowercased --- const ct4 = parse('IMAGE/SVG+XML') // => { type: 'image/svg+xml', parameters: {} } const ct5 = parse('text/html; Charset=UTF-8') // => { type: 'text/html', parameters: { charset: 'UTF-8' } } // Note: parameter name is lowercased; value preserves original casing // --- Quoted parameter values (quotes are stripped) --- const ct6 = parse('text/html; charset="UTF-8"') // => { type: 'text/html', parameters: { charset: 'UTF-8' } } // --- Quoted values containing escaped characters --- const ct7 = parse('text/html; param="charset=\"utf-8\\"; foo=bar"; bar=foo') // => { type: 'text/html', parameters: { param: 'charset="utf-8"; foo=bar', bar: 'foo' } } // --- Surrounding optional whitespace (OWS) is trimmed --- const ct8 = parse(' text/html ; charset=utf-8 ') // => { type: 'text/html', parameters: { charset: 'utf-8' } } // --- Error handling --- try { parse('text/plain; profile=http://localhost') } catch (err) { console.error(err instanceof TypeError) // true console.error(err.message) // 'invalid parameter format' } try { parse('not-valid') } catch (err) { console.error(err.message) // 'invalid media type' } try { parse(42) } catch (err) { console.error(err.message) // 'argument header is required and must be a string' } ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **type** (string) - The lowercased media type string. - **parameters** (object) - A null-prototype object where keys are lowercased parameter names and values are their string values. #### Response Example ```json { "type": "text/html", "parameters": { "charset": "utf-8" } } ``` ``` -------------------------------- ### Parse basic Content-Type header Source: https://context7.com/fastify/fast-content-type-parse/llms.txt Use this function when the input is expected to always be valid and you want failures to surface loudly. It returns a normalized type and parameters object. ```javascript const { parse } = require('fast-content-type-parse') // --- Basic media type --- const ct1 = parse('text/html') // => { type: 'text/html', parameters: {} } ``` ```javascript // --- With charset parameter --- const ct2 = parse('application/json; charset=utf-8') // => { type: 'application/json', parameters: { charset: 'utf-8' } } ``` ```javascript // --- Multiple parameters --- const ct3 = parse('multipart/form-data; boundary=----WebKitFormBoundary; charset=utf-8') // => { type: 'multipart/form-data', parameters: { boundary: '----WebKitFormBoundary', charset: 'utf-8' } } ``` ```javascript // --- Case normalization: type and parameter names are lowercased --- const ct4 = parse('IMAGE/SVG+XML') // => { type: 'image/svg+xml', parameters: {} } ``` ```javascript const ct5 = parse('text/html; Charset=UTF-8') // => { type: 'text/html', parameters: { charset: 'UTF-8' } } // Note: parameter name is lowercased; value preserves original casing ``` ```javascript // --- Quoted parameter values (quotes are stripped) --- const ct6 = parse('text/html; charset="UTF-8"') // => { type: 'text/html', parameters: { charset: 'UTF-8' } } ``` ```javascript // --- Quoted values containing escaped characters --- const ct7 = parse('text/html; param="charset=\"utf-8\\"; foo=bar"; bar=foo') // => { type: 'text/html', parameters: { param: 'charset="utf-8"; foo=bar', bar: 'foo' } } ``` ```javascript // --- Surrounding optional whitespace (OWS) is trimmed --- const ct8 = parse(' text/html ; charset=utf-8 ') // => { type: 'text/html', parameters: { charset: 'utf-8' } } ``` -------------------------------- ### fastContentTypeParse.parse(string) Source: https://github.com/fastify/fast-content-type-parse/blob/main/README.md Parses a Content-Type header string according to RFC 7231. It returns an object containing the media type and its parameters. Throws a TypeError if the string is invalid. ```APIDOC ## fastContentTypeParse.parse(string) ### Description Parses a `Content-Type` header string. Throws a `TypeError` if the string is invalid. ### Method `fastContentTypeParse.parse(string)` ### Parameters #### Path Parameters - **string** (string) - Required - The Content-Type header string to parse. ### Response #### Success Response (Object) - **type** (string) - The media type (type and subtype, always lowercase). - **parameters** (object) - An object of the parameters in the media type (parameter names always lowercase). ### Request Example ```js const fastContentTypeParse = require('fast-content-type-parse') const contentType = fastContentTypeParse.parse('application/json; charset=utf-8') // contentType will be { type: 'application/json', parameters: { charset: 'utf-8' } } ``` ### Response Example ```json { "type": "application/json", "parameters": { "charset": "utf-8" } } ``` ``` -------------------------------- ### defaultContentType Source: https://context7.com/fastify/fast-content-type-parse/llms.txt A shared, frozen sentinel object `{ type: '', parameters: {} }` returned by `safeParse` for invalid or non-string inputs. Useful for efficient reference equality checks. ```APIDOC ## defaultContentType ### Description A frozen, shared object `{ type: '', parameters: {} }` returned by `safeParse` on any invalid or non-string input. It uses a null-prototype object for `parameters` (just like valid parse results), is deeply frozen with `Object.freeze`, and is reused across calls to avoid repeated allocations. You can use reference equality (`=== defaultContentType`) for efficient "was the header invalid?" checks. ### Type Object ### Properties - **type** (string) - The media type, always `''` for this object. - **parameters** (object) - An empty object `{}`, representing no parameters. ### Usage Example ```js const { safeParse, defaultContentType } = require('fast-content-type-parse') // The object is frozen defaultContentType.type = 'text/html' // no effect defaultContentType.parameters.foo = 'bar' // no effect console.log(defaultContentType.type) // '' console.log(Object.keys(defaultContentType.parameters).length) // 0 // Reference equality check const result = safeParse(req.headers['content-type']) if (result === defaultContentType) { // header was absent, non-string, or malformed } ``` ``` -------------------------------- ### safeParse(header) Source: https://context7.com/fastify/fast-content-type-parse/llms.txt Parses a Content-Type header string without throwing errors. Returns a default object for invalid or non-string inputs, suitable for hot paths and untrusted headers. ```APIDOC ## safeParse(header) ### Description Parses a `Content-Type` header string identically to `parse`, but never throws. When the input is not a string, has an invalid media type, or contains malformed parameters, it returns the shared frozen `defaultContentType` object `{ type: '', parameters: {} }`. Use this variant in hot paths, stream pipelines, or middleware where untrusted or potentially malformed headers arrive and you prefer a fallback-check pattern over try/catch. ### Parameters #### Path Parameters - **header** (string) - Required - The Content-Type header string to parse. ### Response #### Success Response (object) - **type** (string) - The media type (e.g., 'application/json'). - **parameters** (object) - An object containing key-value pairs of the header parameters (e.g., `{ charset: 'utf-8' }`). #### Failure Response (defaultContentType object) - **type** (string) - Always `''`. - **parameters** (object) - Always `{}`. ### Request Example ```js const { safeParse, defaultContentType } = require('fast-content-type-parse') // Valid input const ct1 = safeParse('application/json; charset=utf-8') // => { type: 'application/json', parameters: { charset: 'utf-8' } } // Invalid media type returns defaultContentType const ct2 = safeParse('not-valid') // => { type: '', parameters: {} } // Non-string input returns defaultContentType const ct3 = safeParse(null) // => { type: '', parameters: {} } // Malformed parameters return defaultContentType const ct6 = safeParse('text/plain; profile=http://localhost') // => { type: '', parameters: {} } // Check against the sentinel using reference equality if (safeParse(someHeader) === defaultContentType) { console.log('Header was missing or invalid') } ``` ``` -------------------------------- ### fastContentTypeParse.safeParse(string) Source: https://github.com/fastify/fast-content-type-parse/blob/main/README.md Safely parses a Content-Type header string. It does not throw an error for invalid input, instead returning an object with an empty type and parameters. ```APIDOC ## fastContentTypeParse.safeParse(string) ### Description Safely parses a `Content-Type` header string. It will not throw an Error if the header is invalid. ### Method `fastContentTypeParse.safeParse(string)` ### Parameters #### Path Parameters - **string** (string) - Required - The Content-Type header string to parse. ### Response #### Success Response (Object) - **type** (string) - The media type (type and subtype, always lowercase). In case of invalid input, this will be an empty string. - **parameters** (object) - An object of the parameters in the media type (parameter names always lowercase). In case of invalid input, this will be an empty object. ### Request Example ```js const fastContentTypeParse = require('fast-content-type-parse') const contentType = fastContentTypeParse.safeParse('application/json; charset=utf-8') // contentType will be { type: 'application/json', parameters: { charset: 'utf-8' } } const invalidContentType = fastContentTypeParse.safeParse('invalid-header') // invalidContentType will be { type: '', parameters: {} } ``` ### Response Example ```json { "type": "application/json", "parameters": { "charset": "utf-8" } } ``` ### Invalid Response Example ```json { "type": "", "parameters": {} } ``` ``` -------------------------------- ### Handle errors with parse function Source: https://context7.com/fastify/fast-content-type-parse/llms.txt The `parse` function throws a `TypeError` for malformed input. Use a try-catch block to handle these exceptions gracefully. ```javascript // --- Error handling --- try { parse('text/plain; profile=http://localhost') } catch (err) { console.error(err instanceof TypeError) // true console.error(err.message) // 'invalid parameter format' } ``` ```javascript try { parse('not-valid') } catch (err) { console.error(err.message) // 'invalid media type' } ``` ```javascript try { parse(42) } catch (err) { console.error(err.message) // 'argument header is required and must be a string' } ``` -------------------------------- ### Safe Content-Type Header Parsing Source: https://context7.com/fastify/fast-content-type-parse/llms.txt Use `safeParse` for untrusted or potentially malformed headers to avoid exceptions. It returns a default object for invalid inputs, allowing for a fallback-check pattern. ```javascript const { safeParse, defaultContentType } = require('fast-content-type-parse') // --- Valid input behaves the same as parse --- const ct1 = safeParse('application/json; charset=utf-8') // => { type: 'application/json', parameters: { charset: 'utf-8' } } // --- Invalid media type returns defaultContentType (no throw) --- const ct2 = safeParse('not-valid') // => { type: '', parameters: {} } // --- Non-string input returns defaultContentType (no throw) --- const ct3 = safeParse(null) const ct4 = safeParse(undefined) const ct5 = safeParse() // => all: { type: '', parameters: {} } // --- Malformed parameters return defaultContentType (no throw) --- const ct6 = safeParse('text/plain; profile=http://localhost') // => { type: '', parameters: {} } // --- Check against the sentinel using reference equality --- if (safeParse(someHeader) === defaultContentType) { console.log('Header was missing or invalid') } // --- Practical middleware usage (e.g., in a Fastify/Node.js HTTP handler) --- function handleRequest (req, res) { const contentType = safeParse(req.headers['content-type']) if (contentType.type === 'application/json') { const charset = contentType.parameters.charset || 'utf-8' // proceed to parse JSON body with detected charset } else if (contentType.type === 'multipart/form-data') { const boundary = contentType.parameters.boundary if (!boundary) { res.writeHead(400) res.end('Missing multipart boundary') return } // proceed to parse multipart body } else if (contentType.type === '') { res.writeHead(415) res.end('Unsupported or missing Content-Type') return } } ``` -------------------------------- ### Parse Content-Type Header Source: https://github.com/fastify/fast-content-type-parse/blob/main/README.md Use `fastContentTypeParse.parse` to parse a Content-Type header string. This function throws a TypeError for invalid input. It returns an object with 'type' and 'parameters'. ```javascript const contentType = fastContentTypeParse.parse('application/json; charset=utf-8') ``` -------------------------------- ### Default Content-Type Sentinel Object Source: https://context7.com/fastify/fast-content-type-parse/llms.txt The `defaultContentType` object serves as a frozen sentinel for invalid or missing headers when using `safeParse`. Use reference equality (`===`) for efficient checks. ```javascript const { safeParse, defaultContentType } = require('fast-content-type-parse') // The object is frozen — mutation attempts are silently ignored (or throw in strict mode) defaultContentType.type = 'text/html' // no effect defaultContentType.parameters.foo = 'bar' // no effect console.log(defaultContentType.type) // '' console.log(Object.keys(defaultContentType.parameters).length) // 0 // Reference equality check — cheaper than inspecting .type const result = safeParse(req.headers['content-type']) if (result === defaultContentType) { // header was absent, non-string, or malformed } ``` -------------------------------- ### Safely Parse Content-Type Header Source: https://github.com/fastify/fast-content-type-parse/blob/main/README.md Use `fastContentTypeParse.safeParse` to parse a Content-Type header string without throwing errors on invalid input. Returns an object with 'type' and 'parameters', or empty values if the header is invalid. ```javascript const contentType = fastContentTypeParse.safeParse('application/json; charset=utf-8') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.