diff --git a/cli.js b/cli.js index a8e1db6..fc8f2b0 100755 --- a/cli.js +++ b/cli.js @@ -2,19 +2,26 @@ 'use strict'; const meow = require('meow'); const opn = require('opn'); +const getStdin = require('get-stdin'); +const tempWrite = require('temp-write'); +const fileType = require('file-type'); const cli = meow(` Usage $ opn [--wait] [-- [args]] + $ stdout | opn [--wait] [--ext] [-- [args]] Options --wait Wait for the app to exit + --ext File extension for stdin Examples $ opn http://sindresorhus.com $ opn http://sindresorhus.com -- firefox $ opn http://sindresorhus.com -- 'google chrome' --incognito $ opn unicorn.png + $ cat ./image.png | opn + $ echo '[]' | opn --ext json `, { default: { wait: false @@ -23,4 +30,19 @@ const cli = meow(` cli.flags.app = cli.input.slice(1); -opn(cli.input[0], cli.flags); +const input = cli.input[0]; + +if (!input && process.stdin.isTTY) { + console.error('Input required'); + process.exit(1); +} + +if (input) { + opn(input, cli.flags); +} else { + getStdin.buffer().then(stdin => { + const type = fileType(stdin); + const ext = (cli.flags.ext || type && type.ext || 'txt'); + opn(tempWrite.sync(stdin, `opn.${ext}`), cli.flags); + }); +} diff --git a/package.json b/package.json index d382de9..c4bc3a3 100644 --- a/package.json +++ b/package.json @@ -51,8 +51,11 @@ "file" ], "dependencies": { + "file-type": "^3.6.0", + "get-stdin": "^5.0.1", "meow": "^3.7.0", - "opn": "^4.0.0" + "opn": "^4.0.0", + "temp-write": "^2.1.0" }, "devDependencies": { "ava": "*", diff --git a/readme.md b/readme.md index 31172a6..65b70c5 100644 --- a/readme.md +++ b/readme.md @@ -17,15 +17,19 @@ $ opn --help Usage $ opn [--wait] [-- [args]] + $ stdout | opn [--wait] [--ext] [-- [args]] Options --wait Wait for the app to exit + --ext File extension for stdin Examples $ opn http://sindresorhus.com $ opn http://sindresorhus.com -- firefox $ opn http://sindresorhus.com -- 'google chrome' --incognito $ opn unicorn.png + $ cat ./image.png | opn + $ echo '[]' | opn --ext json ```