multispinner

repository·master·Indexed 43 days ago

https://github.com/codekirei/node-multispinner

A Node.js module for managing multiple simultaneous asynchronous CLI spinners. Version 0.2.1 allows for live updates to individual progress indicators in any order, making it ideal for tracking concurrent tasks such as those using Promise.all(). It provides a Multispinner class that extends EventEmitter to handle lifecycle events like done, success, and err.

Tokens
2.4K
Snippets
9
Records
12
Agent score
55%

What's inside multispinner

  1. Overview of node-multispinner

    master
    node-multispinner is a Node.js module designed for managing multiple progress indicators (spinners) in CLI applications. It is particularly effective for applications performing simultaneous asynchronous tasks (such as those using Promise.all[]), as it allows for live updates to individual spinners in any order without interrupting the animation of other active spinners.
  2. Explore multispinner usage examples

    master

    The repository contains several illustrative examples of how to use the module in different scenarios:

    • events.js: Demonstrates creating spinners from an array and responding to success and err completion events using staggered setTimeout calls.
    • customAnimation.js: Shows how to define a custom spinner animation using the frames option.
    • randomInfiniteLoop.js: Demonstrates creating a variable number of spinners with random text that complete randomly in an infinite loop.
    • cli-with-promises: A practical example of a CLI app that uses Promise.all() to execute multiple HTTP GET requests in parallel, with a dedicated spinner for each URL.

    To run these examples, navigate to the extras/examples directory and use node:

    $ node <example_filename>
    $ node <example>
  3. Initialize Multispinner with spinners and options

    master

    Create a new Multispinner instance by providing a spinners collection and an optional options configuration object.

    Spinners

    You can define spinners in two ways:

    1. Array of strings: Each string acts as both the unique ID and the display text. Duplicate strings will cause the constructor to throw.
    2. Object: Use a key: val format where key is the unique ID and val is the display text.

    Options

    Configurable settings include:

    • autoStart (default: true): If false, you must manually call .start().
    • clear (default: false): If true, clears the terminal output using logUpdate.clear() once all spinners finish.
    • frames (default: ['-', '\', '|', '/']): Array of strings used for the animation cycle.
    • indent (default: 2): Number of character widths to indent spinners.
    • interval (default: 80): Milliseconds between animation frames.
    • preText (default: ''): Text inserted after the animation but before the spinner text.
    • postText (default: ''): Text appended after the spinner text.
    • color (default: { incomplete: 'blue', success: 'green', error: 'red' }): Uses Chalk compatible values. You can override specific states (e.g., { incomplete: 'yellow' }).
    • symbol (default: { success: figures.tick, error: figures.cross }): Uses Figures by default. Any string is acceptable.
    // Using an array
    var multispinner = new Multispinner(['Foo', 'Bar', 'Baz']);
    
    // Using an object
    var multispinner = new Multispinner({
      'Foo': 'Downloading Foo',
      'Bar': 'Transpiling Bar',
      'Baz': 'Writing Baz'
    });
    
    // Using options
    var multispinner = new Multispinner(['foo', 'bar'], {
      autoStart: false,
      clear: true,
      preText: 'Completing'
    });
  4. Handle Multispinner completion events

    master

    The Multispinner class extends EventEmitter and emits events when spinners reach a terminal state:

    • done: Emitted when all spinners have completed (regardless of whether they succeeded or errored).
    • success: Emitted when all spinners are complete and every single one is in the success state. If any spinner was marked with .error(), this event will not fire.
    • err: Emitted after all spinners are complete if any were marked with .error(). This event fires once for each failed spinner and emits the ID of the failed spinner as the payload. Note the name is err, not error (to avoid conflict with standard JS Error handling).
    // Listen for total completion
    multispinner.on('done', () => {
      console.log('All spinners are finished');
    });
    
    // Listen for total success
    multispinner.on('success', () => {
      console.log('Everything finished successfully!');
    });
    
    // Listen for individual errors
    multispinner.on('err', (spinnerId) => {
      console.log(`spinner ${spinnerId} had an error`);
    });
  5. Control spinner lifecycle with start(), success(), and error()

    master

    Use these methods to manage the state and animation of your spinners:

    • multispinner.start(): Starts the animation. Only call this if autoStart was set to false in the constructor. Calling it when autoStart is true will cause double-speed animation and dropped frames.
    • multispinner.success(spinner): Marks a specific spinner (by its string ID) as completed with a success state. This updates its symbol and color.
    • multispinner.error(spinner): Marks a specific spinner (by its string ID) as completed with an error state. This updates its symbol and color.
    const multispinner = new Multispinner(['foo', 'bar'], { preText: 'Downloading' });
    
    const fooTask = new Promise((resolve, reject) => {
      // async work
    });
    
    fooTask
      .then((res) => {
        multispinner.success('foo');
      })
      .catch((err) => {
        multispinner.error('foo');
      });
  6. Configure Multispinner options

    master

    When instantiating Multispinner, you can pass an opts object to customize the animation behavior. Common options include:

    • interval: The delay between animation frames (in milliseconds).
    • autoStart: If true, the animation loop starts immediately upon construction.
    • frames: An array of strings representing the animation frames.
    • indent: Number of spaces to indent the spinners.
    • preText: Text to display before the spinners.
    • postText: Text to display after the spinners.
    • color: An object mapping states to chalk colors.
    • clear: If true, the spinners are cleared from the terminal once all are completed.
  7. Check spinner completion status

    master

    Use these methods to programmatically inspect the state of the multispinner instance:

    • allCompleted(): Returns true if every spinner's state is no longer incomplete.
    • allSuccess(): Returns true if every spinner's state is exactly success.
    • anyErrors(): Returns an array of strings containing the names of all spinners currently in the error state.
  8. Control spinner states with success() and error()

    master

    You can manually transition a specific spinner to a terminal state using the success(spinner) or error(spinner) methods. This will update the visual symbol and trigger the appropriate events when all spinners reach a completed state.

    // Assuming 'ms' is an instance of Multispinner
    
    // Mark a specific spinner as successful
    ms.success('task1');
    
    // Mark a specific spinner as failed
    ms.error('task2');
  9. Instantiate Multispinner

    master

    The Multispinner class is the main entrypoint for managing multiple concurrent progress indicators in the terminal. It extends EventEmitter, allowing you to listen for lifecycle events like done, success, or err.

    const Multispinner = require('node-multispinner');
    
    const spinners = {
      task1: 'Downloading files...',
      task2: 'Installing dependencies...'
    };
    
    const opts = {
      interval: 100,
      autoStart: true
    };
    
    const ms = new Multispinner(spinners, opts);
  10. Listen to Multispinner lifecycle events

    master

    Since Multispinner is an EventEmitter, you can react to the completion of the entire batch of spinners.

    • done: Emitted when all spinners have moved out of the incomplete state.
    • success: Emitted if all spinners reached the success state.
    • err: Emitted for each spinner that reached the error state. The event payload is the name of the spinner.
    ms.on('done', () => {
      console.log('All tasks finished!');
    });
    
    ms.on('success', () => {
      console.log('Everything succeeded!');
    });
    
    ms.on('err', (spinnerName) => {
      console.error(`Task failed: ${spinnerName}`);
    });