ora

repository·main·Indexed 26 days ago

https://github.com/sindresorhus/ora

An elegant terminal spinner library for Node.js (version 9.4.1) that provides customizable animations for CLI applications. It includes features for managing spinner lifecycles via methods like .start(), .succeed(), and .fail(), as well as oraPromise for automatically managing spinners around Promises. It supports custom colors, indentation, and stream redirection, and handles console logging without breaking animations.

Tokens
3K
Snippets
7
Records
18
Agent score
92%

What's inside ora

  1. Use Ora in Node.js Worker threads

    main

    Ora cannot animate inside Worker threads because they are not considered interactive terminal environments. To use Ora with workers, run the spinner in the main thread and communicate status updates (like text changes or completion) from the worker via messages.

    // main.js
    import {Worker} from 'node:worker_threads';
    import ora from 'ora';
    
    const spinner = ora().start();
    const worker = new Worker('./worker.js');
    
    worker.on('message', message => {
    	switch (message.type) {
    		case 'ora:text':
    			spinner.text = message.text;
    			break;
    		case 'ora:succeed':
    			spinner.succeed(message.text);
    			break;
    		case 'ora:fail':
    			spinner.fail(message.text);
    			break;
    	}
    });
    
    // worker.js
    import {parentPort} from 'node:worker_threads';
    
    parentPort.postMessage({type: 'ora:text', text: 'Working...'});
    
    // Do work...
    
    parentPort.postMessage({type: 'ora:succeed', text: 'Done!'});
  2. Change the color of the spinner text

    main

    To include colored text within the spinner's message, use a library like chalk or yoctocolors to format the string passed to ora().

    import ora from 'ora';
    import chalk from 'chalk';
    
    const spinner = ora(`Loading ${chalk.red('unicorns')}`).start();
  3. Log messages while a spinner is running

    main

    Ora automatically handles writes to the same stream. When you use console.log() (stdout) or console.error()/console.warn() (stderr), Ora will temporarily clear itself, output your message, and then re-render the spinner below the message. This ensures clean output without breaking the spinner animation.

    const spinner = ora('Processing...').start();
    
    console.log('Step 1 complete');
    console.log('Step 2 complete');
    
    spinner.succeed('Done!');
  4. Basic Usage of ora

    main

    Import ora and initialize it with a string or an options object. Call .start() to begin the animation. You can dynamically update the color and text properties of the spinner instance while it is running.

    import ora from 'ora';
    
    const spinner = ora('Loading unicorns').start();
    
    setTimeout(() => {
    	spinner.color = 'yellow';
    	spinner.text = 'Loading rainbows';
    }, 1000);
  5. Use oraPromise for Promises

    main

    Use oraPromise to automatically manage a spinner for a Promise or a function that returns a Promise. The spinner will automatically call .succeed() if the promise resolves or .fail() if it rejects.

    Options for oraPromise:

    • action: A Promise or a function (spinner: Ora) => Promise.
    • successText (string | ((result: T) => string)): Text to show when resolved.
    • failText (string | ((error: unknown) => string)): Text to show when rejected.
    • successSymbol (string): Custom symbol for success.
    • failSymbol (string): Custom symbol for failure.
    import {oraPromise} from 'ora';
    
    await oraPromise(somePromise);
  6. Configure ora with options

    main

    When calling ora(options), you can pass a configuration object to customize the spinner's appearance and behavior.

    Available Options:

    • text (string): The text to display next to the spinner.
    • prefixText (string | () => string): Text or a function returning text to display before the spinner.
    • suffixText (string | () => string): Text or a function returning text to display after the spinner text.
    • spinner (string | object): The name of a spinner (default: 'dots') or a custom object like { frames: ['-', '+', '-'], interval: 80 }.
    • color (string | false): Spinner color. Values: 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray' | false. Defaults to 'cyan'.
    • hideCursor (boolean): Whether to hide the cursor (default: true).
    • indent (number): Number of spaces to indent the spinner (default: 0).
    • interval (number): Interval between frames (default: provided by spinner or 100).
    • stream (stream.Writable): Stream to write output to (default: process.stderr).
    • isEnabled (boolean): Force enable/disable the spinner.
    • isSilent (boolean): Suppress all output (default: false).
    • discardStdin (boolean): Discard stdin input while running (default: true). Note: This puts stdin into raw mode; use async APIs to keep Ctrl+C responsive.
  7. Manage the Ora Instance

    main

    An Ora instance provides methods to control the lifecycle and appearance of the spinner:

    • .start(text?): Starts the spinner. Returns the instance.
    • .stop(): Stops and clears the spinner. Returns the instance.
    • .succeed(text?): Stops the spinner and shows a green . Returns the instance.
    • .fail(text?): Stops the spinner and shows a red . Returns the instance.
    • .warn(text?): Stops the spinner and shows a yellow . Returns the instance.
    • .info(text?): Stops the spinner and shows a blue . Returns the instance.
    • .stopAndPersist(options?): Stops the spinner and replaces it with a custom symbol and text. Returns the instance.
    • .clear(): Clears the spinner. Returns the instance.
    • .render(): Manually renders a new frame. Returns the instance.
    • .frame(): Gets a new frame.

    Instance Properties (get/set):

    • .text: The text displayed after the spinner.
    • .prefixText: Text before the spinner.
    • .suffixText: Text after the spinner text.
    • .color: The spinner color.
    • .spinner: The spinner animation.
    • .indent: The spinner indent.
    • .isSpinning: Boolean indicating if currently spinning.
    • .isEnabled: Whether the spinner and log text are enabled.
    • .isSilent: Whether all output is suppressed.
    • .interval: The interval between frames.
  8. Configure Ora instance options

    main

    When initializing ora(options), you can provide the following configuration keys:

    • text: The text to display next to the spinner.
    • color: A valid color string (e.g., 'cyan', 'red', 'green') or false to disable color.
    • spinner: A spinner object (from cli-spinners) or a string name of a built-in spinner.
    • interval: A positive integer defining the animation interval in milliseconds.
    • stream: The writable stream to use (defaults to process.stderr).
    • indent: An integer representing the number of spaces to indent the spinner.
    • prefixText: Text to display before the spinner.
    • suffixText: Text to display after the spinner.
    • isEnabled: A boolean to enable/disable the spinner (defaults to checking if the stream is interactive).
    • isSilent: A boolean to suppress all output.
    • hideCursor: Whether to hide the terminal cursor (defaults to true).
    • discardStdin: Whether to discard stdin input while spinning (defaults to true).
  9. Initialize and use Ora

    main

    You can create a spinner by calling the default ora function. If you pass a string, it is treated as the text option. You can then call .start() to begin the animation.

    You can dynamically update the spinner's text or color while it is running.

    import ora from 'ora';
    
    const spinner = ora('Loading unicorns').start();
    
    setTimeout(() => {
    	spinner.color = 'yellow';
    	spinner.text = 'Loading rainbows';
    }, 1000);
  10. Use oraPromise to wrap asynchronous actions

    main
    The oraPromise function allows you to wrap a Promise or a function that returns a Promise with a spinner. The spinner automatically starts, and based on the outcome of the promise, it will call .succeed() or .fail() with optional custom text.