/
cli.js
executable file
·67 lines (60 loc) · 1.64 KB
/
cli.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env node
import process from 'node:process';
import meow from 'meow';
import open from 'open';
import getStdin from 'get-stdin';
import {temporaryWrite} from 'tempy';
import {fileTypeFromBuffer} from 'file-type';
const cli = meow(`
Usage
$ open-cli <file|url> [--wait] [--background] [-- <app> [args]]
$ cat <file> | open-cli [--extension] [--wait] [--background] [-- <app> [args]]
Options
--wait Wait for the app to exit
--background Do not bring the app to the foreground (macOS only)
--extension File extension for when stdin file type cannot be detected
Examples
$ open-cli https://sindresorhus.com
$ open-cli https://sindresorhus.com -- firefox
$ open-cli https://sindresorhus.com -- 'google chrome' --incognito
$ open-cli unicorn.png
$ cat unicorn.png | open-cli
$ echo '<h1>Unicorns!</h1>' | open-cli --extension=html
`, {
importMeta: import.meta,
flags: {
wait: {
type: 'boolean',
default: false,
},
background: {
type: 'boolean',
default: false,
},
extension: {
type: 'string',
},
},
});
const input = cli.input[0];
const options = cli.flags;
if (!input && process.stdin.isTTY) {
console.error('Specify a file path or URL');
process.exit(1);
}
const [, appName, ...appArguments] = cli.input;
if (appName) {
options.app = {
name: appName,
arguments: appArguments,
};
}
if (input) {
await open(input, options);
} else {
const stdin = await getStdin.buffer();
const type = await fileTypeFromBuffer(stdin);
const extension = cli.flags.extension ?? type?.ext ?? 'txt';
const filePath = await temporaryWrite(stdin, {extension});
await open(filePath, options);
}