bin.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env node
  2. var minimist = require('minimist')
  3. var ndjson = require('ndjson')
  4. var fs = require('fs')
  5. var csv = require('./')
  6. var argv = minimist(process.argv, {
  7. alias: {
  8. h: 'headers',
  9. v: 'version',
  10. o: 'output',
  11. s: 'separator',
  12. q: 'quote',
  13. e: 'escape'
  14. },
  15. default: {
  16. s: ',',
  17. q: '"',
  18. e: '"'
  19. },
  20. boolean: ['version', 'help']
  21. })
  22. var headers = argv.headers && argv.headers.toString().split(argv.separator)
  23. var filename = argv._[2]
  24. if (argv.version) {
  25. console.log(require('./package').version)
  26. process.exit(0)
  27. }
  28. if (argv.help || (process.stdin.isTTY && !filename)) {
  29. console.error(
  30. 'Usage: csv-parser [filename?] [options]\n\n' +
  31. ' --headers,-h Explicitly specify csv headers as a comma separated list\n' +
  32. ' --output,-o Set output file. Defaults to stdout\n' +
  33. ' --separator,-s Set the separator character ("," by default)\n' +
  34. ' --quote,-q Set the quote character (\'"\' by default)\n' +
  35. ' --escape,-e Set the escape character (defaults to quote value)\n' +
  36. ' --strict Require column length match headers length\n' +
  37. ' --version,-v Print out the installed version\n' +
  38. ' --remove Remove headers from output\n' +
  39. ' --help Show this help\n'
  40. )
  41. process.exit(1)
  42. }
  43. var input
  44. var output = (argv.output && argv.output !== '-') ? fs.createWriteStream(argv.output) : process.stdout
  45. var removedHeaders = argv.remove && argv.remove.split(',')
  46. function mapHeaders (name, i) {
  47. return removedHeaders.indexOf(name) === -1 ? name : null
  48. }
  49. if (filename === '-' || !filename) {
  50. input = process.stdin
  51. } else if (fs.existsSync(filename)) {
  52. input = fs.createReadStream(filename)
  53. } else {
  54. console.error('File: %s does not exist', filename)
  55. process.exit(2)
  56. }
  57. input
  58. .pipe(csv({
  59. headers: headers,
  60. separator: argv.separator,
  61. strict: argv.strict,
  62. mapHeaders: argv.remove ? mapHeaders : null
  63. }))
  64. .pipe(ndjson.serialize())
  65. .pipe(output)