Created
November 3, 2017 11:32
-
-
Save johndstein/8b33991ae014d3707057c303f757ac63 to your computer and use it in GitHub Desktop.
Didn't help
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const { | |
promisify | |
} = require('util'); | |
function handle(err) { | |
console.error(err.stack || err); | |
process.exit(3); | |
} | |
exports = module.exports = function(opts) { | |
const parser = require('csv-parse')( | |
Object.assign({ | |
columns: true | |
}, opts.parse)); | |
const stringer = require('csv-stringify')( | |
Object.assign({ | |
header: true | |
}, opts.stringify)); | |
const transformer = new require('stream').Transform({ | |
transform(row, encoding, cb) { | |
// opts.transform.bind(transformer)(row, cb); | |
const trAsync = promisify(opts.transform.bind(transformer)); | |
trAsync(row) | |
.then((result) => { | |
cb(null, result); | |
}) | |
.catch((err) => { | |
cb(err) | |
}); | |
}, | |
flush(cb) { | |
if (opts.flush) { | |
opts.flush.bind(transformer)(cb); | |
} else { | |
cb(); | |
} | |
}, | |
objectMode: true | |
}); | |
(opts.in || process.stdin).on('error', handle) | |
.pipe(parser).on('error', handle) | |
.pipe(transformer).on('error', handle) | |
.pipe(stringer).on('error', handle) | |
.pipe(opts.out || process.stdout).on('error', handle); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment