csv-parser 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/usr/bin/env node
  2. const { EOL } = require('os')
  3. const minimist = require('minimist')
  4. const { Transform } = require('stream');
  5. const fs = require('fs')
  6. const csv = require('../')
  7. const pkg = require('../package.json')
  8. const argv = minimist(process.argv, {
  9. alias: {
  10. c: 'skipComments',
  11. e: 'escape',
  12. h: 'headers',
  13. o: 'output',
  14. q: 'quote',
  15. l: 'skipLines',
  16. s: 'separator',
  17. v: 'version'
  18. },
  19. default: {
  20. e: '"',
  21. q: '"',
  22. s: ','
  23. },
  24. boolean: ['version', 'help']
  25. })
  26. const [,, filename] = argv._
  27. if (argv.version) {
  28. console.log(pkg.version)
  29. process.exit(0)
  30. }
  31. if (argv.help || (process.stdin.isTTY && !filename)) {
  32. console.error(`Usage: csv-parser [filename?] [options]
  33. --escape,-e Set the escape character (defaults to quote value)
  34. --headers,-h Explicitly specify csv headers as a comma separated list
  35. --help Show this help
  36. --output,-o Set output file. Defaults to stdout
  37. --quote,-q Set the quote character ('"' by default)
  38. --remove Remove headers from output
  39. --separator,-s Set the separator character ("," by default)
  40. --skipComments,-c Skip CSV comments that begin with '#'. Set a value to change the comment character.
  41. --skipLines,-l Set the number of lines to skip to before parsing headers
  42. --strict Require column length match headers length
  43. --version,-v Print out the installed version
  44. `)
  45. process.exit(1)
  46. }
  47. let input
  48. const output = (argv.output && argv.output !== '-') ? fs.createWriteStream(argv.output) : process.stdout
  49. const options = {
  50. separator: argv.separator,
  51. strict: argv.strict,
  52. skipComments: argv.skipComments,
  53. skipLines: argv.skipLines
  54. }
  55. if (argv.headers) {
  56. options.headers = argv.headers.toString().split(argv.separator)
  57. }
  58. if (argv.remove) {
  59. const removeHeaders = argv.remove.split(',')
  60. options.mapHeaders = (name, i) => {
  61. return removeHeaders.indexOf(name) === -1 ? name : null
  62. }
  63. }
  64. if (filename === '-' || !filename) {
  65. input = process.stdin
  66. } else if (fs.existsSync(filename)) {
  67. input = fs.createReadStream(filename)
  68. } else {
  69. console.error(`File: ${filename} does not exist`)
  70. process.exit(2)
  71. }
  72. const serialize = () => {
  73. return new Transform({
  74. objectMode: true,
  75. transform(obj, enc, cb) {
  76. cb(null, JSON.stringify(obj) + EOL)
  77. }
  78. });
  79. }
  80. input
  81. .pipe(csv(options))
  82. .pipe(serialize())
  83. .pipe(output)