diff --git a/Readme.md b/Readme.md index 4e46bd1..c9529ea 100644 --- a/Readme.md +++ b/Readme.md @@ -72,6 +72,8 @@ 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 }, ...] + // a function can be passed to columns to map the array of columns + // columns: (cols) => cols.map(col => col.toLowerCase()) columns: false } ``` diff --git a/csv-streamify.js b/csv-streamify.js index 1e128af..736e262 100644 --- a/csv-streamify.js +++ b/csv-streamify.js @@ -11,7 +11,7 @@ var through = require('through2') * @param {string} [opts.quote='"'] The quote character * @param {string} [opts.empty=''] Which character to return for empty fields * @param {boolean} [opts.objectMode=true] Whether to return an object or a buffer per line - * @param {boolean} [opts.columns=false] Whether to parse headers + * @param {boolean|function} [opts.columns=false] Whether to parse headers or a function to parse headers * @param {function} [cb] Callback function */ module.exports = function (opts, cb) { @@ -53,7 +53,11 @@ function createParser (opts, state) { if (opts.hasColumns) { if (state.lineNo === 0) { - state._columns = state._line + if (typeof opts.hasColumns === 'function') { + state._columns = opts.hasColumns(state._line) + } else { + state._columns = state._line + } state.lineNo += 1 reset() return diff --git a/test/csv-streamify.js b/test/csv-streamify.js index 6327969..81deb26 100644 --- a/test/csv-streamify.js +++ b/test/csv-streamify.js @@ -157,6 +157,19 @@ describe('object mode', function () { str('COL0,COL1\ncol0,col1\ncol2,col3').pipe(parser) }) + + it('should emit multiple columns parsed by custom function', function (done) { + var parser = csv({ + columns: (cols) => cols.map(col => col.toLowerCase()) + }, function (err, res) { + if (err) return done(err) + assert.deepEqual(res[0], { col0: 'col0', col1: 'col1' }) + assert.deepEqual(res[1], { col0: 'col2', col1: 'col3' }) + done() + }) + + str('COL0,COL1\ncol0,col1\ncol2,col3').pipe(parser) + }) }) describe('edge cases', function () {