3 * Copyright(c) 2014-2015 Douglas Christopher Wilson
10 * Module dependencies.
13 var bytes = require('bytes')
14 var contentType = require('content-type')
15 var debug = require('debug')('body-parser:text')
16 var read = require('../read')
17 var typeis = require('type-is')
26 * Create a middleware to parse text bodies.
28 * @param {object} [options]
33 function text(options) {
34 var opts = options || {}
36 var defaultCharset = opts.defaultCharset || 'utf-8'
37 var inflate = opts.inflate !== false
38 var limit = typeof opts.limit !== 'number'
39 ? bytes.parse(opts.limit || '100kb')
41 var type = opts.type || 'text/plain'
42 var verify = opts.verify || false
44 if (verify !== false && typeof verify !== 'function') {
45 throw new TypeError('option verify must be function')
48 // create the appropriate type checking function
49 var shouldParse = typeof type !== 'function'
57 return function textParser(req, res, next) {
59 return debug('body already parsed'), next()
62 req.body = req.body || {}
64 // skip requests without bodies
65 if (!typeis.hasBody(req)) {
66 return debug('skip empty body'), next()
69 debug('content-type %j', req.headers['content-type'])
71 // determine if request should be parsed
72 if (!shouldParse(req)) {
73 return debug('skip parsing'), next()
77 var charset = getCharset(req) || defaultCharset
80 read(req, res, next, parse, debug, {
90 * Get the charset of a request.
96 function getCharset(req) {
98 return contentType.parse(req).parameters.charset.toLowerCase()
105 * Get the simple type checker.
107 * @param {string} type
111 function typeChecker(type) {
112 return function checkType(req) {
113 return Boolean(typeis(req, type))