The `content-type` package provides a robust utility for creating and parsing HTTP Content-Type headers in Node.js applications, adhering strictly to RFC 7231. It is currently at version 1.0.5, indicating a mature and stable library. The release cadence is infrequent, primarily focusing on performance improvements and minor fixes, suggesting a low-churn, well-maintained codebase. Its core functionality involves parsing a Content-Type string (or directly from `req`/`res` objects) into an object with `type` and `parameters`, and conversely, formatting such an object back into a valid header string. This library is a foundational component for many HTTP servers and clients that need reliable content negotiation, differentiating itself through its minimalist API and strict RFC compliance without unnecessary abstractions.
npm install content-typeVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates parsing Content-Type headers from strings and simulated HTTP requests, and formatting objects back into header strings.
```javascript
try {
const parsed = contentType.parse(headerValue);
// ... use parsed object
} catch (error) {
if (error instanceof TypeError) {
console.error('Invalid Content-Type header:', error.message);
// Handle invalid header, e.g., return 400 Bad Request
} else {
throw error;
}
}
``````javascript
const header = req.headers['content-type'];
if (header) {
try {
const parsed = contentType.parse(header);
// ...
} catch (error) {
// Handle invalid format
}
} else {
console.warn('Content-Type header is missing.');
// Handle missing header explicitly
}
```Review existing usage of `media-typer` and ensure `content-type` provides equivalent functionality and handles error conditions identically. Specifically check how invalid input strings are handled, as `content-type` consistently throws `TypeError`.
Ensure that a non-empty string is always passed to `contentType.parse()`. If parsing from `req.headers['content-type']`, explicitly check if the header exists before calling parse.
Verify the input string's syntax. It should follow the `type/subtype; parameter=value` structure. For example, `text/html`, `application/json; charset=utf-8` are valid, while `html` or `application/json;` (with trailing semicolon) might be invalid.
Ensure the object passed to `contentType.format()` has a `type` property which is a valid media type string (e.g., `'application/json'`, `'text/plain'`).
No dependency data recorded yet.