From 785aba879c189cdd047793e5d4859146427eca48 Mon Sep 17 00:00:00 2001 From: TJ Holowaychuk Date: Fri, 14 Feb 2014 09:38:59 -0800 Subject: [PATCH] add request.charset --- docs/api/request.md | 9 +++++++++ lib/request.js | 16 ++++++++++++++++ test/request/charset.js | 28 ++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 test/request/charset.js diff --git a/docs/api/request.md b/docs/api/request.md index 196e326..a586cef 100644 --- a/docs/api/request.md +++ b/docs/api/request.md @@ -73,6 +73,15 @@ var ct = this.type; // => "image/png" ``` +### res.charset + + Get request charset when present, or `undefined`: + +```js +this.charset +// => "utf-8" +``` + ### req.query Get parsed query-string, returning an empty object when no diff --git a/lib/request.js b/lib/request.js index eda4675..991cc2f 100644 --- a/lib/request.js +++ b/lib/request.js @@ -261,6 +261,22 @@ module.exports = { return this.req.socket; }, + /** + * Get the charset when present or undefined. + * + * @return {String} + * @api public + */ + + get charset() { + // TODO: lame, we could have a generic param parsing lib + var type = this.get('Content-Type'); + if (!type) return; + + var m = type.match(/charset *= *(\S+)/); + if (m) return m[1]; + }, + /** * Return parsed Content-Length when present. * diff --git a/test/request/charset.js b/test/request/charset.js new file mode 100644 index 0000000..df3e51e --- /dev/null +++ b/test/request/charset.js @@ -0,0 +1,28 @@ + +var request = require('../context').request; +var assert = require('assert'); + +describe('req.charset', function(){ + describe('with no content-type present', function(){ + it('should return null', function(){ + var req = request(); + assert(null == req.charset); + }) + }) + + describe('with charset present', function(){ + it('should return null', function(){ + var req = request(); + req.header['content-type'] = 'text/plain'; + assert(null == req.charset); + }) + }) + + describe('with a charset', function(){ + it('should return the charset', function(){ + var req = request(); + req.header['content-type'] = 'text/plain; charset=utf-8'; + req.charset.should.equal('utf-8'); + }) + }) +}) \ No newline at end of file