- Notifications
You must be signed in to change notification settings - Fork34
A terminal based horizontal guage aka, a progress bar
License
npm/gauge
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A nearly stateless terminal based horizontal gauge / progress bar.
varGauge=require("gauge")vargauge=newGauge()gauge.show("working…",0)setTimeout(()=>{gauge.pulse();gauge.show("working…",0.25)},500)setTimeout(()=>{gauge.pulse();gauge.show("working…",0.50)},1000)setTimeout(()=>{gauge.pulse();gauge.show("working…",0.75)},1500)setTimeout(()=>{gauge.pulse();gauge.show("working…",0.99)},2000)setTimeout(()=>gauge.hide(),2300)
See also thedemos:
Gauge 2.x is breaking release, please see thechangelog for details onwhat's changed if you were previously a user of this module.
This is the typical interface to the module– it provides a prettyfire-and-forget interface to displaying your status information.
var Gauge = require("gauge")var gauge = new Gauge([stream], [options])
- stream –(optional, default STDERR) A stream that progress barupdates are to be written to. Gauge honors backpressure and will pausemost writing if it is indicated.
- options –(optional) An option object.
Constructs a new gauge. Gauges are drawn on a single line, and are not drawnifstream isn't a tty and a tty isn't explicitly provided.
Ifstream is a terminal or if you pass intty tooptions then wewill detect terminal resizes and redraw to fit. We do this by watching forresize
events on the tty. (To work around a bug in versions of Node priorto 2.5.0, we watch for them on stdout if the tty is stderr.) Resizes tolarger window sizes will be clean, but shrinking the window will alwaysresult in some cruft.
IMPORTANT: If you previously were passing in a non-tty stream but you stillwant output (for example, a stream wrapped by theansi
module) then youneed to pass in thetty option below, asgauge
needs access tothe underlying tty in order to do things like terminal resizes and terminalwidth detection.
Theoptions object can have the following properties, all of which areoptional:
updateInterval: How often gauge updates should be drawn, in milliseconds.
fixedFramerate: Defaults to false on node 0.8, true on everythingelse. When this is true a timer is created to trigger once every
updateInterval
ms, when false, updates are printed as soon as they comein but updates more often thanupdateInterval
are ignored. The reason0.8 doesn't have this set to true is that it can'tunref
its timer andso it would stop your program from exiting– if you want to use thisfeature with 0.8 just make sure you callgauge.disable()
before youexpect your program to exit.themes: A themeset to use when selecting the theme to use. Defaultsto
gauge/themes
, see thethemes documentation for details.theme: Select a theme for use, it can be a:
- Theme object, in which case thethemes is not used.
- The name of a theme, which will be looked up in the currentthemesobject.
- A configuration object with any of
hasUnicode
,hasColor
orplatform
keys, which if will be used to override our guesses when makinga default theme selection.
If no theme is selected then a default is picked using a combination of ourbest guesses at your OS, color support and unicode support.
template: Describes what you want your gauge to look like. Thedefault is what npm uses. Detaileddocumentation is later in thisdocument.
hideCursor: Defaults to true. If true, then the cursor will be hiddenwhile the gauge is displayed.
tty: The tty that you're ultimately writing to. Defaults to the sameasstream. This is used for detecting the width of the terminal andresizes. The width used is
tty.columns - 1
. If no tty is available thena width of79
is assumed.enabled: Defaults to true if
tty
is a TTY, false otherwise. If truethe gauge starts enabled. If disabled then all update commands areignored and no gauge will be printed until you call.enable()
.Plumbing: The class to use to actually generate the gauge forprinting. This defaults to
require('gauge/plumbing')
and ordinarily youshouldn't need to override this.cleanupOnExit: Defaults to true. Ordinarily we register an exithandler to make sure your cursor is turned back on and the progress barerased when your process exits, even if you Ctrl-C out or otherwise exitunexpectedly. You can disable this and it won't register the exit handler.
The first argument is either the section, the name of the current thingcontributing to progress, or an object with keys likesection,subsection &completed (or any others you have types for in a customtemplate). If you don't want to update or set any of these you can passnull
and it will be ignored.
The second argument is the percent completed as a value between 0 and 1.Without it, completion is just not updated. You'll also note that completioncan be passed in as part of a status object as the first argument. If bothit and the completed argument are passed in, the completed argument wins.
Removes the gauge from the terminal. Optionally, callbackcb
after IO hashad an opportunity to happen (currently this just means aftersetImmediate
has called back.)
It turns out this is important when you're pausing the progress bar on onefilehandle and printing to another– otherwise (with a big enough print) nodecan end up printing the "end progress bar" bits to the progress bar filehandlewhile other stuff is printing to another filehandle. These getting interleavedcan cause corruption in some terminals.
- subsection –(optional) The specific thing that triggered this pulse
Spins the spinner in the gauge to show output. Ifsubsection isincluded then it will be combined with the last name passed togauge.show
.
Hides the gauge and ignores further calls toshow
orpulse
.
Shows the gauge and resumes updating whenshow
orpulse
is called.
Returns true if the gauge is enabled.
Change the themeset to select a theme from. The same as thethemes
optionused in the constructor. The theme will be reselected from this themeset.
Change the active theme, will be displayed with the next show or pulse. This can be:
- Theme object, in which case thethemes is not used.
- The name of a theme, which will be looked up in the currentthemesobject.
- A configuration object with any of
hasUnicode
,hasColor
orplatform
keys, which if will be used to override our guesses when makinga default theme selection.
If no theme is selected then a default is picked using a combination of ourbest guesses at your OS, color support and unicode support.
Change the active template, will be displayed with the next show or pulse
If you have more than one thing going on that you want to track completionof, you may find the relatedare-we-there-yet helpful. It'schange
event can be wired up to theshow
method to get a more traditionalprogress bar interface.
var themes = require('gauge/themes')// fetch the default color unicode theme for this platformvar ourTheme = themes({hasUnicode: true, hasColor: true})// fetch the default non-color unicode theme for osxvar ourTheme = themes({hasUnicode: true, hasColor: false, platform: 'darwin'})// create a new theme based on the color ascii theme for this platform// that brackets the progress bar with arrowsvar ourTheme = themes.newTheme(themes({hasUnicode: false, hasColor: true}), { preProgressbar: '→', postProgressbar: '←'})
The object returned bygauge/themes
is an instance of theThemeSet
class.
var ThemeSet = require('gauge/theme-set')var themes = new ThemeSet()// orvar themes = require('gauge/themes')var mythemes = themes.newThemeSet() // creates a new themeset based on the default themes
Theme objects are a function that fetches the default theme based onplatform, unicode and color support.
Options is an object with the following properties:
- hasUnicode - If true, fetch a unicode theme, if no unicode theme isavailable then a non-unicode theme will be used.
- hasColor - If true, fetch a color theme, if no color theme isavailable a non-color theme will be used.
- platform (optional) - Defaults to
process.platform
. If noplatform match is available thenfallback
is used instead.
If no compatible theme can be found then an error will be thrown with acode
ofEMISSINGTHEME
.
Adds a named theme to the themeset. You can pass in either a theme object,as returned bythemes.newTheme
or the arguments you'd pass tothemes.newTheme
.
Return a list of all of the names of the themes in this themeset. Suitablefor use inthemes.getTheme(…)
.
Returns the theme object from this theme set namedname
.
Ifname
does not exist in this themeset an error will be thrown withacode
ofEMISSINGTHEME
.
opts
is an object with the following properties.
- platform - Defaults to
'fallback'
. If your theme is platformspecific, specify that here with the platform fromprocess.platform
, eg,win32
,darwin
, etc. - hasUnicode - Defaults to
false
. If your theme uses unicode youshould set this to true. - hasColor - Defaults to
false
. If your theme uses color you shouldset this to true.
themeName
is the name of the theme (as given toaddTheme
) to use forthis set ofopts
.
Create a new theme object based onparentTheme
. If noparentTheme
isprovided then a minimal parentTheme that defines functions for rendering theactivity indicator (spinner) and progress bar will be defined. (Thisfallback parent is defined ingauge/base-theme
.)
newTheme should be a bare object– we'll start by discussing the propertiesdefined by the default themes:
- preProgressbar - displayed prior to the progress bar, if the progressbar is displayed.
- postProgressbar - displayed after the progress bar, if the progress baris displayed.
- progressBarTheme - The subtheme passed through to the progress barrenderer, it's an object with
complete
andremaining
propertiesthat are the strings you want repeated for those sections of the progressbar. - activityIndicatorTheme - The theme for the activity indicator (spinner),this can either be a string, in which each character is a different step, oran array of strings.
- preSubsection - Displayed as a separator between the
section
andsubsection
when the latter is printed.
More generally, themes can have any value that would be a valid value when renderingtemplates. The properties in the theme are used when their name matches a type inthe template. Their values can be:
- strings & numbers - They'll be included as is
- function (values, theme, width) - Should return what you want in your output.values is an object with values provided via
gauge.show
,theme is the theme specific to this item (see below) or this theme object,andwidth is the number of characters wide your result should be.
There are a couple of special prefixes:
- pre - Is shown prior to the property, if its displayed.
- post - Is shown after the property, if its displayed.
And one special suffix:
- Theme - Its value is passed to a function-type item as the theme.
Thismixes-intheme
into all themes currently defined. It also adds itto the default parent theme for this themeset, so future themes added tothis themeset will get the values fromtheme
by default.
Copy the current themeset into a new one. This allows you to easily inheritone themeset from another.
A template is an array of objects and strings that, after being evaluated,will be turned into the gauge line. The default template is:
[{type:'progressbar',length:20},{type:'activityIndicator',kerning:1,length:1},{type:'section',kerning:1,default:''},{type:'subsection',kerning:1,default:''}]
The various template elements can either beplain strings, in which case they willbe be included verbatum in the output, or objects with the following properties:
- type can be any of the following plus any keys you pass into
gauge.show
plusany keys you have on a custom theme.section
– What big thing you're working on now.subsection
– What component of that thing is currently working.activityIndicator
– Shows a spinner using theactivityIndicatorTheme
from your active theme.progressbar
– A progress bar representing your currentcompleted
using theprogressbarTheme
from your active theme.
- kerning – Number of spaces that must be between this item and otheritems, if this item is displayed at all.
- maxLength – The maximum length for this element. If its value is longer itwill be truncated.
- minLength – The minimum length for this element. If its value is shorter itwill be padded according to thealign value.
- align – (Default: left) Possible values "left", "right" and "center". Worksas you'd expect from word processors.
- length – Provides a single value for bothminLength andmaxLength. If bothlength and *minLength ormaxLength are specified then the latter take precedence.
- value – A literal value to use for this template item.
- default – A default value to use for this template item if a valuewasn't otherwise passed in.
This is the super simple, assume nothing, do no magic internals used by gauge toimplement its ordinary interface.
var Plumbing = require('gauge/plumbing')var gauge = new Plumbing(theme, template, width)
- theme: The theme to use.
- template: The template to use.
- width: How wide your gauge should be
Change the active theme.
Change the active template.
Change the width to render at.
Return the string necessary to hide the progress bar
Return a string to hide the cursor.
Return a string to show the cursor.
Usingstatus
for values, render the provided template with the theme and returna string that is suitable for printing to update the gauge.
About
A terminal based horizontal guage aka, a progress bar