Skip to content

Instantly share code, notes, and snippets.

@nulltask
Created March 17, 2012 08:46
Show Gist options
  • Save nulltask/2056783 to your computer and use it in GitHub Desktop.
Save nulltask/2056783 to your computer and use it in GitHub Desktop.
Output CSV in Express
/**
* Module dependencies.
*/
var express = require('express')
, app = module.exports = express.createServer();
// Configuration
app.use(app.router);
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
// Routes
app.get('/', function(req, res) {
var data = [
['ID', 'Name', 'Age', 'Gender']
, [1, 'Taro Yamada', 25, 'Male']
, [2, 'Hanako Yamada', 24, 'Female']
, [3, 'John Doe', 30, 'Male']
, [4, 'Jane Doe', 30, 'Female']
];
// CSV Specification
// http://www.ietf.org/rfc/rfc4180.txt
res.statusCode = 200;
res.setHeader('Content-Type', 'text/csv');
data.forEach(function(item) {
res.write(item.map(function(field) {
return '"' + field.toString().replace(/\"/g, '""') + '"';
}).toString() + '\r\n');
});
res.end();
});
// Listen
app.listen(3000);
/**
* Module dependencies.
*/
var express = require('express')
, Iconv = require('iconv').Iconv
, sjis = new Iconv('UTF-8', 'Shift_JIS')
, app = module.exports = express.createServer();
// Configuration
app.use(app.router);
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
// Routes
app.get('/', function(req, res) {
var csv = ''
, data = [
['ID', 'お名前', '年齢', '性別']
, [1, '山田 太郎', 25, '男性']
, [2, '山田 花子', 24, '女性']
];
// CSV Specification
// http://www.ietf.org/rfc/rfc4180.txt
res.statusCode = 200;
res.setHeader('Content-Type', 'text/csv; charset=Shift_JIS');
data.forEach(function(item) {
csv += item.map(function(field) {
return '"="' + field.toString().replace(/\"/g, '""') + '""';
}).toString() + '\r\n';
});
res.write(sjis.convert(csv));
res.end();
});
// Listen
app.listen(3000);
/**
* Module dependencies.
*/
var Iconv = require('iconv').Iconv
, sjis = new Iconv('UTF-8', 'Shift_JIS');
console.log(sjis.convert('世界の皆さん、こんにちは。'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment