版博士V2.0程序
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. <p align="center">
  2. <a href="http://liftoffjs.com">
  3. <img height="100" width="297" src="https://cdn.rawgit.com/tkellen/js-liftoff/master/artwork/liftoff.svg"/>
  4. </a>
  5. </p>
  6. <p align="center">
  7. <a href="http://gulpjs.com">
  8. <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png">
  9. </a>
  10. </p>
  11. # liftoff
  12. [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Coveralls Status][coveralls-image]][coveralls-url]
  13. Launch your command line tool with ease.
  14. ## What is it?
  15. [See this blog post][liftoff-blog], [check out this proof of concept][hacker], or read on.
  16. Say you're writing a CLI tool. Let's call it [hacker]. You want to configure it using a `Hackerfile`. This is node, so you install `hacker` locally for each project you use it in. But, in order to get the `hacker` command in your PATH, you also install it globally.
  17. Now, when you run `hacker`, you want to configure what it does using the `Hackerfile` in your current directory, and you want it to execute using the local installation of your tool. Also, it'd be nice if the `hacker` command was smart enough to traverse up your folders until it finds a `Hackerfile`&mdash;for those times when you're not in the root directory of your project. Heck, you might even want to launch `hacker` from a folder outside of your project by manually specifying a working directory. Liftoff manages this for you.
  18. So, everything is working great. Now you can find your local `hacker` and `Hackerfile` with ease. Unfortunately, it turns out you've authored your `Hackerfile` in coffee-script, or some other JS variant. In order to support _that_, you have to load the compiler for it, and then register the extension for it with node. Good news, Liftoff can do that, and a whole lot more, too.
  19. ## Usage
  20. ```js
  21. const Liftoff = require('liftoff');
  22. const Hacker = new Liftoff({
  23. name: 'hacker',
  24. processTitle: 'hacker',
  25. moduleName: 'hacker',
  26. configName: 'hackerfile',
  27. extensions: {
  28. '.js': null,
  29. '.json': null,
  30. '.coffee': 'coffee-script/register',
  31. },
  32. v8flags: ['--harmony'], // or v8flags: require('v8flags')
  33. });
  34. Hacker.prepare({}, function (env) {
  35. Hacker.execute(env, function (env) {
  36. // Do post-execute things
  37. });
  38. });
  39. ```
  40. ## API
  41. ### constructor(opts)
  42. Create an instance of Liftoff to invoke your application.
  43. #### opts.name
  44. Sugar for setting `processTitle`, `moduleName`, `configName` automatically.
  45. Type: `String`
  46. Default: `null`
  47. These are equivalent:
  48. ```js
  49. const Hacker = Liftoff({
  50. processTitle: 'hacker',
  51. moduleName: 'hacker',
  52. configName: 'hackerfile',
  53. });
  54. ```
  55. ```js
  56. const Hacker = Liftoff({ name: 'hacker' });
  57. ```
  58. Type: `String`
  59. Default: `null`
  60. #### opts.configName
  61. Sets the name of the configuration file Liftoff will attempt to find. Case-insensitive.
  62. Type: `String`
  63. Default: `null`
  64. #### opts.extensions
  65. Set extensions to include when searching for a configuration file. If an external module is needed to load a given extension (e.g. `.coffee`), the module name should be specified as the value for the key.
  66. Type: `Object`
  67. Default: `{".js":null,".json":null}`
  68. **Examples:**
  69. In this example Liftoff will look for `myappfile{.js,.json,.coffee}`. If a config with the extension `.coffee` is found, Liftoff will try to require `coffee-script/require` from the current working directory.
  70. ```js
  71. const MyApp = new Liftoff({
  72. name: 'myapp',
  73. extensions: {
  74. '.js': null,
  75. '.json': null,
  76. '.coffee': 'coffee-script/register',
  77. },
  78. });
  79. ```
  80. In this example, Liftoff will look for `.myapp{rc}`.
  81. ```js
  82. const MyApp = new Liftoff({
  83. name: 'myapp',
  84. configName: '.myapp',
  85. extensions: {
  86. rc: null,
  87. },
  88. });
  89. ```
  90. In this example, Liftoff will automatically attempt to load the correct module for any javascript variant supported by [interpret] (as long as it does not require a register method).
  91. ```js
  92. const MyApp = new Liftoff({
  93. name: 'myapp',
  94. extensions: require('interpret').jsVariants,
  95. });
  96. ```
  97. #### opts.v8flags
  98. Any flag specified here will be applied to node, not your program. Useful for supporting invocations like `myapp --harmony command`, where `--harmony` should be passed to node, not your program. This functionality is implemented using [flagged-respawn]. To support all v8flags, see [v8flags].
  99. Type: `Array` or `Function`
  100. Default: `null`
  101. If this method is a function, it should take a node-style callback that yields an array of flags.
  102. #### opts.processTitle
  103. Sets what the [process title][process-title] will be.
  104. Type: `String`
  105. Default: `null`
  106. #### opts.completions(type)
  107. A method to handle bash/zsh/whatever completions.
  108. Type: `Function`
  109. Default: `null`
  110. #### opts.configFiles
  111. An object of configuration files to find. Each property is keyed by the default basename of the file being found, and the value is an object of [path arguments](#path-arguments) keyed by unique names.
  112. **Note:** This option is useful if, for example, you want to support an `.apprc` file in addition to an `appfile.js`. If you only need a single configuration file, you probably don't need this. In addition to letting you find multiple files, this option allows more fine-grained control over how configuration files are located.
  113. Type: `Object`
  114. Default: `null`
  115. #### Path arguments
  116. The [`fined`][fined] module accepts a string representing the path to search or an object with the following keys:
  117. - `path` **(required)**
  118. The path to search. Using only a string expands to this property.
  119. Type: `String`
  120. Default: `null`
  121. - `name`
  122. The basename of the file to find. Extensions are appended during lookup.
  123. Type: `String`
  124. Default: Top-level key in `configFiles`
  125. - `extensions`
  126. The extensions to append to `name` during lookup. See also: [`opts.extensions`](#optsextensions).
  127. Type: `String` or `Array` or `Object`
  128. Default: The value of [`opts.extensions`](#optsextensions)
  129. - `cwd`
  130. The base directory of `path` (if relative).
  131. Type: `String`
  132. Default: The value of [`opts.cwd`](#optscwd)
  133. - `findUp`
  134. Whether the `path` should be traversed up to find the file.
  135. Type: `Boolean`
  136. Default: `false`
  137. **Examples:**
  138. In this example Liftoff will look for the `.hacker.js` file relative to the `cwd` as declared in `configFiles`.
  139. ```js
  140. const MyApp = new Liftoff({
  141. name: 'hacker',
  142. configFiles: {
  143. '.hacker': {
  144. cwd: '.',
  145. },
  146. },
  147. });
  148. ```
  149. In this example, Liftoff will look for `.hackerrc` in the home directory.
  150. ```js
  151. const MyApp = new Liftoff({
  152. name: 'hacker',
  153. configFiles: {
  154. '.hacker': {
  155. home: {
  156. path: '~',
  157. extensions: {
  158. rc: null,
  159. },
  160. },
  161. },
  162. },
  163. });
  164. ```
  165. In this example, Liftoff will look in the `cwd` and then lookup the tree for the `.hacker.js` file.
  166. ```js
  167. const MyApp = new Liftoff({
  168. name: 'hacker',
  169. configFiles: {
  170. '.hacker': {
  171. up: {
  172. path: '.',
  173. findUp: true,
  174. },
  175. },
  176. },
  177. });
  178. ```
  179. In this example, the `name` is overridden and the key is ignored so Liftoff looks for `.override.js`.
  180. ```js
  181. const MyApp = new Liftoff({
  182. name: 'hacker',
  183. configFiles: {
  184. hacker: {
  185. override: {
  186. path: '.',
  187. name: '.override',
  188. },
  189. },
  190. },
  191. });
  192. ```
  193. In this example, Liftoff will use the home directory as the `cwd` and looks for `~/.hacker.js`.
  194. ```js
  195. const MyApp = new Liftoff({
  196. name: 'hacker',
  197. configFiles: {
  198. '.hacker': {
  199. home: {
  200. path: '.',
  201. cwd: '~',
  202. },
  203. },
  204. },
  205. });
  206. ```
  207. ### prepare(opts, callback(env))
  208. Prepares the environment for your application with provided options, and invokes your callback with the calculated environment as the first argument. The environment can be modified before using it as the first argument to `execute`.
  209. **Example Configuration w/ Options Parsing:**
  210. ```js
  211. const Liftoff = require('liftoff');
  212. const MyApp = new Liftoff({ name: 'myapp' });
  213. const argv = require('minimist')(process.argv.slice(2));
  214. const onExecute = function (env, argv) {
  215. // Do post-execute things
  216. };
  217. const onPrepare = function (env) {
  218. console.log('my environment is:', env);
  219. console.log('my liftoff config is:', this);
  220. MyApp.execute(env, onExecute);
  221. };
  222. MyApp.prepare(
  223. {
  224. cwd: argv.cwd,
  225. configPath: argv.myappfile,
  226. preload: argv.preload,
  227. completion: argv.completion,
  228. },
  229. onPrepare
  230. );
  231. ```
  232. **Example w/ modified environment**
  233. ```js
  234. const Liftoff = require('liftoff');
  235. const Hacker = new Liftoff({
  236. name: 'hacker',
  237. configFiles: {
  238. '.hacker': {
  239. home: { path: '.', cwd: '~' },
  240. },
  241. },
  242. });
  243. const onExecute = function (env, argv) {
  244. // Do post-execute things
  245. };
  246. const onPrepare = function (env) {
  247. env.configProps = ['home', 'cwd']
  248. .map(function (dirname) {
  249. return env.configFiles['.hacker'][dirname];
  250. })
  251. .filter(function (filePath) {
  252. return Boolean(filePath);
  253. })
  254. .reduce(function (config, filePath) {
  255. return mergeDeep(config, require(filePath));
  256. }, {});
  257. if (env.configProps.hackerfile) {
  258. env.configPath = path.resolve(env.configProps.hackerfile);
  259. env.configBase = path.dirname(env.configPath);
  260. }
  261. Hacker.execute(env, onExecute);
  262. };
  263. Hacker.prepare({}, onPrepare);
  264. ```
  265. #### opts.cwd
  266. Change the current working directory for this execution. Relative paths are calculated against `process.cwd()`.
  267. Type: `String`
  268. Default: `process.cwd()`
  269. **Example Configuration:**
  270. ```js
  271. const argv = require('minimist')(process.argv.slice(2));
  272. MyApp.prepare(
  273. {
  274. cwd: argv.cwd,
  275. },
  276. function (env) {
  277. MyApp.execute(env, invoke);
  278. }
  279. );
  280. ```
  281. **Matching CLI Invocation:**
  282. ```
  283. myapp --cwd ../
  284. ```
  285. #### opts.configPath
  286. Don't search for a config, use the one provided. **Note:** Liftoff will assume the current working directory is the directory containing the config file unless an alternate location is explicitly specified using `cwd`.
  287. Type: `String`
  288. Default: `null`
  289. **Example Configuration:**
  290. ```js
  291. var argv = require('minimist')(process.argv.slice(2));
  292. MyApp.prepare(
  293. {
  294. configPath: argv.myappfile,
  295. },
  296. function (env) {
  297. MyApp.execute(env, invoke);
  298. }
  299. );
  300. ```
  301. **Matching CLI Invocation:**
  302. ```sh
  303. myapp --myappfile /var/www/project/Myappfile.js
  304. ```
  305. **Examples using `cwd` and `configPath` together:**
  306. These are functionally identical:
  307. ```sh
  308. myapp --myappfile /var/www/project/Myappfile.js
  309. myapp --cwd /var/www/project
  310. ```
  311. These can run myapp from a shared directory as though it were located in another project:
  312. ```sh
  313. myapp --myappfile /Users/name/Myappfile.js --cwd /var/www/project1
  314. myapp --myappfile /Users/name/Myappfile.js --cwd /var/www/project2
  315. ```
  316. #### opts.preload
  317. A string or array of modules to attempt requiring from the local working directory before invoking the execute callback.
  318. Type: `String|Array`
  319. Default: `null`
  320. **Example Configuration:**
  321. ```js
  322. var argv = require('minimist')(process.argv.slice(2));
  323. MyApp.prepare(
  324. {
  325. preload: argv.preload,
  326. },
  327. function (env) {
  328. MyApp.execute(env, invoke);
  329. }
  330. );
  331. ```
  332. **Matching CLI Invocation:**
  333. ```sh
  334. myapp --preload coffee-script/register
  335. ```
  336. #### callback(env)
  337. A function called after your environment is prepared. A good place to modify the environment before calling `execute`. When invoked, `this` will be your instance of Liftoff. The `env` param will contain the following keys:
  338. - `cwd`: the current working directory
  339. - `preload`: an array of modules that liftoff tried to pre-load
  340. - `configNameSearch`: the config files searched for
  341. - `configPath`: the full path to your configuration file (if found)
  342. - `configBase`: the base directory of your configuration file (if found)
  343. - `modulePath`: the full path to the local module your project relies on (if found)
  344. - `modulePackage`: the contents of the local module's package.json (if found)
  345. - `configFiles`: an object of filepaths for each found config file (filepath values will be null if not found)
  346. ### execute(env, [forcedFlags], callback(env, argv))
  347. A function to start your application, based on the `env` given. Optionally takes an array of `forcedFlags`, which will force a respawn with those node or V8 flags during startup. Invokes your callback with the environment and command-line arguments (minus node & v8 flags) after the application has been executed.
  348. **Example:**
  349. ```js
  350. const Liftoff = require('liftoff');
  351. const MyApp = new Liftoff({ name: 'myapp' });
  352. const onExecute = function (env, argv) {
  353. // Do post-execute things
  354. console.log('my environment is:', env);
  355. console.log('my cli options are:', argv);
  356. console.log('my liftoff config is:', this);
  357. };
  358. const onPrepare = function (env) {
  359. var forcedFlags = ['--trace-deprecation'];
  360. MyApp.execute(env, forcedFlags, onExecute);
  361. };
  362. MyApp.prepare({}, onPrepare);
  363. ```
  364. #### callback(env, argv)
  365. A function called after your application is executed. When invoked, `this` will be your instance of Liftoff, `argv` will be all command-line arguments (minus node & v8 flags), and `env` will contain the following keys:
  366. - `cwd`: the current working directory
  367. - `preload`: an array of modules that liftoff tried to pre-load
  368. - `configNameSearch`: the config files searched for
  369. - `configPath`: the full path to your configuration file (if found)
  370. - `configBase`: the base directory of your configuration file (if found)
  371. - `modulePath`: the full path to the local module your project relies on (if found)
  372. - `modulePackage`: the contents of the local module's package.json (if found)
  373. - `configFiles`: an object of filepaths for each found config file (filepath values will be null if not found)
  374. ### events
  375. #### `on('preload:before', function(name) {})`
  376. Emitted before a module is pre-load. (But for only a module which is specified by `opts.preload`.)
  377. ```js
  378. var Hacker = new Liftoff({ name: 'hacker', preload: 'coffee-script' });
  379. Hacker.on('preload:before', function (name) {
  380. console.log('Requiring external module: ' + name + '...');
  381. });
  382. ```
  383. #### `on('preload:success', function(name, module) {})`
  384. Emitted when a module has been pre-loaded.
  385. ```js
  386. var Hacker = new Liftoff({ name: 'hacker' });
  387. Hacker.on('preload:success', function (name, module) {
  388. console.log('Required external module: ' + name + '...');
  389. // automatically register coffee-script extensions
  390. if (name === 'coffee-script') {
  391. module.register();
  392. }
  393. });
  394. ```
  395. #### `on('preload:failure', function(name, err) {})`
  396. Emitted when a requested module cannot be preloaded.
  397. ```js
  398. var Hacker = new Liftoff({ name: 'hacker' });
  399. Hacker.on('preload:failure', function (name, err) {
  400. console.log('Unable to load:', name, err);
  401. });
  402. ```
  403. #### `on('loader:success, function(name, module) {})`
  404. Emitted when a loader that matches an extension has been loaded.
  405. ```js
  406. var Hacker = new Liftoff({
  407. name: 'hacker',
  408. extensions: {
  409. '.ts': 'ts-node/register',
  410. },
  411. });
  412. Hacker.on('loader:success', function (name, module) {
  413. console.log('Required external module: ' + name + '...');
  414. });
  415. ```
  416. #### `on('loader:failure', function(name, err) {})`
  417. Emitted when no loader for an extension can be loaded. Emits an error for each failed loader.
  418. ```js
  419. var Hacker = new Liftoff({
  420. name: 'hacker',
  421. extensions: {
  422. '.ts': 'ts-node/register',
  423. },
  424. });
  425. Hacker.on('loader:failure', function (name, err) {
  426. console.log('Unable to load:', name, err);
  427. });
  428. ```
  429. #### `on('respawn', function(flags, child) {})`
  430. Emitted when Liftoff re-spawns your process (when a [`v8flags`](#optsv8flags) is detected).
  431. ```js
  432. var Hacker = new Liftoff({
  433. name: 'hacker',
  434. v8flags: ['--harmony'],
  435. });
  436. Hacker.on('respawn', function (flags, child) {
  437. console.log('Detected node flags:', flags);
  438. console.log('Respawned to PID:', child.pid);
  439. });
  440. ```
  441. Event will be triggered for this command:
  442. `hacker --harmony commmand`
  443. ## Examples
  444. Check out how [gulp][gulp-cli-index] uses Liftoff.
  445. For a bare-bones example, try [the hacker project][hacker-index].
  446. To try the example, do the following:
  447. 1. Install the sample project `hacker` with `npm install -g hacker`.
  448. 2. Make a `Hackerfile.js` with some arbitrary javascript it.
  449. 3. Install hacker next to it with `npm install hacker`.
  450. 4. Run `hacker` while in the same parent folder.
  451. ## License
  452. MIT
  453. <!-- prettier-ignore-start -->
  454. [downloads-image]: https://img.shields.io/npm/dm/liftoff.svg?style=flat-square
  455. [npm-url]: https://www.npmjs.com/package/liftoff
  456. [npm-image]: https://img.shields.io/npm/v/liftoff.svg?style=flat-square
  457. [ci-url]: https://github.com/gulpjs/liftoff/actions?query=workflow:dev
  458. [ci-image]: https://img.shields.io/github/workflow/status/gulpjs/liftoff/dev?style=flat-square
  459. [coveralls-url]: https://coveralls.io/r/gulpjs/liftoff
  460. [coveralls-image]: https://img.shields.io/coveralls/gulpjs/liftoff/master.svg?style=flat-square
  461. <!-- prettier-ignore-end -->
  462. <!-- prettier-ignore-start -->
  463. [liftoff-blog]: https://bocoup.com/blog/building-command-line-tools-in-node-with-liftoff
  464. [hacker]: https://github.com/gulpjs/hacker
  465. [interpret]: https://github.com/gulpjs/interpret
  466. [flagged-respawn]: http://github.com/gulpjs/flagged-respawn
  467. [v8flags]: https://github.com/gulpjs/v8flags
  468. [fined]: https://github.com/gulpjs/fined
  469. [process-title]: http://nodejs.org/api/process.html#process_process_title
  470. [gulp-cli-index]: https://github.com/gulpjs/gulp-cli/blob/master/index.js
  471. [hacker-index]: https://github.com/gulpjs/js-hacker/blob/master/bin/hacker.js
  472. <!-- prettier-ignore-end -->