diff --git a/src/cli.js b/src/cli.js index 9e72cbe..b85453d 100755 --- a/src/cli.js +++ b/src/cli.js @@ -18,31 +18,62 @@ function getArgs() { '$0 -c AwesomeComponent awesome.htm', 'Creates React component "AwesomeComponent" based on awesome.htm' ) + .example( + 'cat file.htm | $0 -c AwesomeComponent', + 'Creates React component "AwesomeComponent" based on data piped in' + ) .strict(); var files = args.argv._; - if (!files || files.length === 0) { - console.error('Please provide a file name'); - args.showHelp(); - process.exit(1); + + // print error if called directly (not piped) and no files are specified + if (process.stdin.isTTY && (!files || files.length === 0)) { + console.error('Please provide a file name'); + args.showHelp(); + process.exit(1); } return args.argv; } -function main() { - var argv = getArgs(); - fs.readFile(argv._[0], 'utf-8', function(err, input) { +function buildConverterCb(createClass, outputClassName) { + var converter = new HTMLtoJSX({ + createClass: createClass, + outputClassName: outputClassName + }); + + return function(err, input) { if (err) { console.error(err.stack); process.exit(2); } - var converter = new HTMLtoJSX({ - createClass: !!argv.className, - outputClassName: argv.className - }); + var output = converter.convert(input); console.log(output); + process.exit(); + } +} + +function readFromPipe(cb) { + var data = ''; + process.stdin.resume() + process.stdin.setEncoding('utf8') + process.stdin.on('data', function(chunk) { + data += chunk; + }); + process.stdin.on('end', function() { + return cb(null, data); }); } + +function main() { + var argv = getArgs(); + var convertInputCb = buildConverterCb(!!argv.className, argv.className); + + if (process.stdin.isTTY) { + return fs.readFile(argv._[0], 'utf-8', convertInputCb); + } + return readFromPipe(convertInputCb); +} + main();