Skip to content

Instantly share code, notes, and snippets.

@nbkhope nbkhope/app.js forked from nulltask/app.js
Created Mar 16, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.