Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,12 @@ The options are also passed to the underlying transform stream, so you can pass
objectMode: false,

// if set to true, uses first row as keys -> [ { column1: value1, column2: value2 }, ...]
columns: false
columns: false,

// each csv column name is optionally mapped to this so its value can be transformed
columnTransform: function(name) {
return name
}
}
```

Expand Down
3 changes: 2 additions & 1 deletion csv-streamify.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ module.exports = function (opts, cb) {
opts.empty = opts.hasOwnProperty('empty') ? opts.empty : ''
opts.objectMode = opts.objectMode || false
opts.hasColumns = opts.columns || false
opts.columnTransform = opts.columnTransform || function (l) { return l }

// state
var state = {
Expand All @@ -41,7 +42,7 @@ function createParser (opts, state) {

if (opts.hasColumns) {
if (state.lineNo === 0) {
state._columns = state._line
state._columns = state._line.map(opts.columnTransform)
state.lineNo += 1
reset()
return
Expand Down
42 changes: 42 additions & 0 deletions test/csv-streamify.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,45 @@ describe('edge cases', function () {
}))
})
})

describe('column name transform', function () {
it('should transform column names', function (done) {
var input = 'Some Name,product_description,watchers\n'
input += 'SLaks/Styliner,"Turns CSS stylesheets into inline style="""" attributes for HTML emails",33\n'
input += 'guelfey/go.dbus,Native Go bindings for D-Bus,12'

var opts = {
columns: true,
columnTransform: function (name) {
switch (name) {
case 'Some Name':
return 'newName'
case 'product_description':
return 'productDescription'
default:
return name
}
}
}

str(input).pipe(csv(opts, function (err, res) {
if (err) return done(err)

assert.strictEqual(res.length, 2, 'should emit 2 lines')

assert.strictEqual(res[0].hasOwnProperty('Some Name'), false)
assert.strictEqual(res[0]['newName'], 'SLaks/Styliner')
assert.strictEqual(res[0].hasOwnProperty('product_description'), false)
assert.strictEqual(res[0]['productDescription'], 'Turns CSS stylesheets into inline style="" attributes for HTML emails')
assert.strictEqual(res[0]['watchers'], '33')

assert.strictEqual(res[1].hasOwnProperty('Some Name'), false)
assert.strictEqual(res[1]['newName'], 'guelfey/go.dbus')
assert.strictEqual(res[1].hasOwnProperty('product_description'), false)
assert.strictEqual(res[1]['productDescription'], 'Native Go bindings for D-Bus')
assert.strictEqual(res[1]['watchers'], '12')

done()
}))
})
})