Skip to content

Commit

Permalink
Merge pull request #1 from alexcrack/encodings
Browse files Browse the repository at this point in the history
Utilize iconv-lite to handle cyrillic data
  • Loading branch information
jczaplew committed Oct 16, 2015
2 parents 54adc85 + fd2ce3a commit fa78bec
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/csv-express.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'use strict';

var res = require('http').ServerResponse.prototype;
var iconv = require('iconv-lite');

// Configurable settings
exports.separator = ',';
Expand Down Expand Up @@ -92,5 +93,9 @@ res.csv = function(data, csvHeaders, headers, status) {
body += item.map(escape).join(exports.separator) + '\r\n';
});

if (this.charset !== 'utf-8') {
body = iconv.encode(body, this.charset);
}

return this.send(body, headers, status);
}
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,8 @@
"scripts": {
"test": "mocha",
"prepublish": "make test"
},
"dependencies": {
"iconv-lite": "^0.4.13"
}
}
34 changes: 34 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,19 @@ app.get('/test/objectArray', function(req, res) {
]);
});

app.get('/test/cyrillic/utf8', function(req, res) {
res.csv([
['Привет', 'мир']
]);
});

app.get('/test/cyrillic/cp1251', function(req, res) {
res.charset = "cp-1251";
res.csv([
['Привет', 'мир']
]);
});

app.listen(8383);

describe('csv-express', function() {
Expand Down Expand Up @@ -195,4 +208,25 @@ describe('res.csv()', function() {
done();
});
});

describe('when given cyrillyc data', function() {
it('should response with utf-8 text', function(done) {
request
.get('http://127.0.0.1:8383/test/cyrillic/utf8')
.end(function(error, res) {
res.text.should.equal('"Привет","мир"\r\n');
done();
});
});

it('should response with cp-1251 text', function(done) {
request
.get('http://127.0.0.1:8383/test/cyrillic/cp1251')
.end(function(error, res) {
var text = new Buffer([0x22, 0xcf, 0xf0, 0xe8, 0xe2, 0xe5, 0xf2, 0x22, 0x2c, 0x22, 0xcc, 0xe8, 0xf0, 0x22, 0x0d, 0x0a]);
res.text.should.equal(text.toString());
done();
});
});
});
});

0 comments on commit fa78bec

Please sign in to comment.