diff --git a/Readme.md b/Readme.md index c8d5112..975f378 100644 --- a/Readme.md +++ b/Readme.md @@ -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 + } } ``` diff --git a/csv-streamify.js b/csv-streamify.js index 32f2633..254853e 100644 --- a/csv-streamify.js +++ b/csv-streamify.js @@ -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 = { @@ -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 diff --git a/test/csv-streamify.js b/test/csv-streamify.js index 413581e..19a3fe8 100644 --- a/test/csv-streamify.js +++ b/test/csv-streamify.js @@ -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() + })) + }) +})