easy-json-stream
Advanced tools
Comparing version 1.2.0 to 1.3.0
19
index.js
@@ -29,2 +29,16 @@ var Transform = require('stream').Transform | ||
util.inherits(CSVStream, Transform); | ||
function CSVStream(options) { | ||
Transform.call(this, { objectMode: true }); | ||
this.count = 0; | ||
} | ||
CSVStream.prototype._transform = function(chunk, enc, next) { | ||
var chunks = []; | ||
if (++this.count < 2) | ||
chunks.push(Object.keys(chunk).join(',')); | ||
chunks.push(Object.keys(chunk).map(function(key) { return chunk[key] }).join(',')); | ||
chunks.forEach(this.push.bind(this)); | ||
next(); | ||
} | ||
util.inherits(ParseStream, Transform); | ||
@@ -55,5 +69,8 @@ function ParseStream(options) { | ||
}, | ||
csv: function csv(options) { | ||
return new CSVStream(options); | ||
}, | ||
parse: function parse(options) { | ||
return new ParseStream(options); | ||
} | ||
} | ||
} |
{ | ||
"name": "easy-json-stream", | ||
"version": "1.2.0", | ||
"version": "1.3.0", | ||
"description": "Stream objects to JSON and JSON into objects.", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -13,2 +13,3 @@ var path = require('path') | ||
t.ok(json.parse, 'parse is a thing'); | ||
t.ok(json.csv, 'csv is a thing'); | ||
t.end(); | ||
@@ -105,2 +106,24 @@ }); | ||
stream.end(); | ||
}); | ||
}); | ||
test('csv', function(t) { | ||
var data = [{ one: 1, two: 2, three: 3 }, { one: 'i', two: 'ii', three: 'iii' }] | ||
, readable = new stream.Readable({ objectMode: true }) | ||
, buffer = [] | ||
; | ||
readable._read = function(){}; | ||
readable | ||
.pipe(json.csv()) | ||
.on('data', buffer.push.bind(buffer)) | ||
.once('data', function(chunk) { | ||
var headers = chunk.split(','); | ||
t.deepEquals(headers, ['one', 'two', 'three'], 'it should emit the headers first'); | ||
}) | ||
.on('end', function() { | ||
t.equals(buffer[1], '1,2,3', 'it should emit rows of data'); | ||
t.end(); | ||
}).resume() | ||
; | ||
data.forEach(readable.push.bind(readable)); | ||
readable.push(null); | ||
}); |
8525
195