add request.charset

This commit is contained in:
TJ Holowaychuk 2014-02-14 09:38:59 -08:00
parent 94413b1bd4
commit 785aba879c
3 changed files with 53 additions and 0 deletions

View file

@ -73,6 +73,15 @@ var ct = this.type;
// => "image/png" // => "image/png"
``` ```
### res.charset
Get request charset when present, or `undefined`:
```js
this.charset
// => "utf-8"
```
### req.query ### req.query
Get parsed query-string, returning an empty object when no Get parsed query-string, returning an empty object when no

View file

@ -261,6 +261,22 @@ module.exports = {
return this.req.socket; 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. * Return parsed Content-Length when present.
* *

28
test/request/charset.js Normal file
View file

@ -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');
})
})
})