@vikhola/content-type
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

@vikhola/content-type

About

Plugin that parses HTTP Content-Type headers.

Installation

$ npm i @vikhola/content-type

Usage

Package could be required as ES6 module

import { ContentType } from '@vikhola/content-type'

Or as commonJS module.

const { ContentType } = require('@vikhola/content-type');

class: ContentType

The ContentType accepts an optional type and parameters that will be assigned to its instance.

const contentType = new ContentType('text/html', { charset: 'utf-8', foo: 'bar' });

If type is not a string or contains invalid characters, an error will be thrown.

// throw an Error
const contentType = new ContentType('text/html\n');

contentType.type

The contentType.type is current Content-Type type.

const contentType = new ContentType('text/html')

// print: text/html
console.log(contentType.type);

contentType.params

The contentType.params a object that contains the current type parameters.

const contentType = new ContentType('text/html', { charset: 'utf-8', foo: 'bar' });

// print: { charset: 'utf-8', foo: 'bar' }
console.log(contentType.params);

ContentType.from()

The contentType.from() static method takes an HTTP Content-Type header, parses it, and returns a new ContentType instance with the type and params.

const contentType = ContentType.from('text/html; charset=utf-8; foo=bar')

// print: text/html
console.log(contentType.type)

// print: { charset: 'utf-8', foo: 'bar' }
console.log(contentType.params)

If the content type header is not a string or some parameters contain invalid characters, the ContentType instance will have an empty type property and an empty params object after initialization.

const contentType = ContentType.from('text/\nhtml; charset=utf-8; foo=bar')

// print: ''
console.log(contentType.type)

// print: {}
console.log(contentType.params)

contentType.toString()

Return a string representation suitable to be sent as HTTP header.

const contentType = new ContentType()

contentType.type = 'text/html'

// print: text/html
console.log(contentType.toString())

contentType.params = { charset: 'utf-8', foo: 'bar' }

// print: text/html; charset=utf-8; foo=bar
console.log(contentType.toString())

License

MIT

Readme

Keywords

Package Sidebar

Install

npm i @vikhola/content-type

Weekly Downloads

19

Version

1.0.0

License

MIT

Unpacked Size

12 kB

Total Files

7

Last publish

Collaborators

  • sabaziosd