Coder Social home page Coder Social logo

usmanyunusov / nanospinner Goto Github PK

View Code? Open in Web Editor NEW
188.0 2.0 15.0 125 KB

๐ŸŒ€ The simplest and tiniest terminal spinner for Node.js

Home Page: https://npm.im/nanospinner

License: ISC License

JavaScript 100.00%
spinner spinners terminal

nanospinner's Introduction

Nano Spinner

The simplest and tiniest terminal spinner for Node.js

import { createSpinner } from 'nanospinner'

const spinner = createSpinner('Run test').start()

setTimeout(() => {
  spinner.success()
}, 1000)
  • Only single dependency (picocolors).
  • It 45 times smaller than ora.
  • Support both CJS and ESM projects.
  • TypeScript type declarations included.

Motivation

With nanospinner we are trying to draw attention to the node_modules size problem and promote performance-first culture.

Benchmarks

The space in node_modules including sub-dependencies:

$ node ./test/size.js
Data from packagephobia.com
  ora           597 kB
+ nanospinner    13 kB

API

.spin()

Looping over spin method will animate a given spinner.

setInterval(() => {
  spinner.spin()
}, 25)

.start(options?)

In order to start the spinner call start. This will perform drawing the spinning animation

spinner.start()
spinner.start({ text: 'Start', color: 'yellow' })

.stop(options?)

In order to stop the spinner call stop. This will finish drawing the spinning animation and return to new line.

spinner.stop()
spinner.stop({ text: 'Done!', mark: ':O', color: 'magenta' })

.success(options?)

Use success call to stop the spinning animation and replace the spinning symbol with check mark character to indicate successful completion.

spinner.success()
spinner.success({ text: 'Successful!', mark: ':)' })

.warn(options?)

Use warn call to stop the spinning animation and replace the spinning symbol with warn mark character to indicate warning completion.

spinner.warn()
spinner.warn({ text: 'Warning!', mark: ':|' })

.error(options?)

Use error call to stop the spinning animation and replace the spinning symbol with cross character to indicate error completion.

spinner.error()
spinner.error({ text: 'Error!', mark: ':(' })

.update(options?)

Use update call to dynamically change

spinner.update({
  text: 'Run test',
  color: 'white',
  stream: process.stdout,
  frames: ['.', 'o', '0', '@', '*'],
  interval: 100,
})

.clear()

Clears the spinner`s output

spinner.clear()

.reset()

In order to reset the spinner to its initial frame do:

spinner.reset()

Roadmap

  • Multi spinners

nanospinner's People

Contributors

ai avatar asyncbanana avatar epszaw avatar kikobeats avatar mmustra avatar mrozio13pl avatar trysound avatar usmanyunusov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

nanospinner's Issues

Node throws memory leak warning causing script to fail

I am currently working on a node script to update a dataset generated from a bunch fetch requests. I decided to add nanospinners to the fetchData function I have set up to fetch one or multiple json endpoints and it appears to have caused a memory leak:

(node:17186) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 SIGINT listeners added to [process]. Use emitter.setMaxListeners() to increase limit
    at _addListener (events.js:390:17)
    at process.addListener (events.js:406:10)
    at Object.start (/home/mitsunee/Projects/fgo-tools/node_modules/nanospinner/index.js:54:15)
    at fetchData (file:///home/mitsunee/Projects/fgo-tools/scripts/update-upgrades-data.mjs:230:11)
    at fetchQuestData (file:///home/mitsunee/Projects/fgo-tools/scripts/update-upgrades-data.mjs:245:42)
    at main (file:///home/mitsunee/Projects/fgo-tools/scripts/update-upgrades-data.mjs:401:44)

Here is an excerpt from the script in question (I haven't pushed my changes yet, so I'm copypasting it here for reference)

async function fetchData(url, defaultValue, message = "Fetching Data") {
  const spinner = createSpinner(message);
  const _fetch = async (url, defaultValue) => {
    try {
      const res = await fetch(url);
      if (!res.ok) {
        if (defaultValue === undefined) {
          spinner.error(`error while fetching '${url}'`);
          process.exit(2);
        }
        return defaultValue;
      }
      return await res.json();
    } catch (e) {
      if (defaultValue === undefined) {
        spinner.error(`received invalid data from '${url}'`);
        process.exit(2);
      }
      return defaultValue;
    }
  };

  let res;
  spinner.start();
  if (url instanceof Array) {
    res = await Promise.all(
      url.map(async item => await _fetch(item, defaultValue))
    );
  } else {
    res = await _fetch(url, defaultValue);
  }
  spinner.success();
  return res;
}

The fetch() api is provided by node-fetch. The warning occurs after this function has ran 10 times, causing it to return invalid data (possibly undefined?). fetchQuestData is merely a wrapper around fetchData() that caches results in a Map. It appears the warning is thrown here:

https://github.com/usmanyunusov/nanospinner/blob/master/index.js#L47-L57

Not restore cursor when the program exits abnormally

When exiting in the loading state (e.g. ctrl + c), the cursor is still hidden.

Do you think it's better to listen to SIGINT to restore the cursor when exit?

(Willing to contribute a PR for this. Also if there is anything inappropriate please point it out directly :)

Does not adhere to license

nanospinner/consts.js

Lines 4 to 9 in b53e875

process.env.CI ||
process.env.WT_SESSION ||
process.env.ConEmuTask === '{cmd::Cmder}' ||
process.env.TERM_PROGRAM === 'vscode' ||
process.env.TERM === 'xterm-256color' ||
process.env.TERM === 'alacritty'
is clearly directly copied from: https://github.com/sindresorhus/is-unicode-supported/blob/8f123916d5c25a87c4f966dcc248b7ca5df2b4ca/index.js


nanospinner/consts.js

Lines 15 to 16 in b53e875

? ['โ ‹', 'โ ™', 'โ น', 'โ ธ', 'โ ผ', 'โ ด', 'โ ฆ', 'โ ง', 'โ ‡', 'โ ']
: ['-', '\\', '|', '/']
is copied from https://github.com/sindresorhus/cli-spinners


And

nanospinner/consts.js

Lines 18 to 20 in b53e875

tick: supportUnicode ? 'โœ”' : 'โˆš',
cross: supportUnicode ? 'โœ–' : 'ร—',
warn: supportUnicode ? 'โš ' : '!!',
is copied from https://github.com/sindresorhus/log-symbols/blob/main/index.js

Suggestion: move error handling to method

What do you think about moving this to a method:

function bindExit() {
  process.on('SIGINT', () => {
      spinner.stop();
      process.exit();
  });
}

You could also handle more exit types like:

function bindExit() {
  [
      'SIGHUP',
      'SIGINT',
      'SIGQUIT',
      'SIGTERM',
      'uncaughtException'
  ]
  .forEach(eventType => process.on(eventType, () => {
      spinner.stop();
      process.exit();
  }));
}

Can't show 2 spinners at the same time

Hi ๐Ÿ‘‹๐Ÿป

I'm trying to setup 2 spinners at the same time, but it looks like i can't. My code:

import { createSpinner } from 'nanospinner';

const a = createSpinner('Spinner A').start();
const b = createSpinner('Spinner B').start();
setTimeout(() => {
  a.success();
  b.success();
  process.exit(0);
}, 3000);

Result:

Record_select-area_20220426144326

Only dahs instead of spinner

When i start the spinner i see only dash:

Capture

This is the code i used for spinner:
const spinner = createSpinner("Installing dependencies...");
spinner.start();

Feature Request: A way to use console methods while a spinner is running

Current Behaviour:
console methods (like log, warn, table) print in a line that already contains a frame of the spinner.

Expected Behaviour:
No spinner is visible in the line a console method prints to

Suggestion:
Either a pause or togglePause method (pausing hides the spinner, leaving an empty line for any logger to print to) or a log method specifically for this use case.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.