swiss-node
TypeScript icon, indicating that this package has built-in type declarations

3.1.4 • Public • Published

swiss-node

Swiss Army Knife for node

A collection of helper functions and useful little things for node.js

Uses swiss-ak

ask

A collection of functions to ask the user for input.

[↑ Back to top ↑]

text

ask.text(question: string | Breadcrumb, initial: string, validate: (value: string) => Error | string | boolean | void, lc: LineCounter): Promise<string>

Get a text input from the user.

const name = await ask.text('What is your name?'); // 'Jack'
# Parameter Name Required Type
0 question Yes string | Breadcrumb
1 initial No string
2 validate No (value: string) => Error | string | boolean | void
3 lc No LineCounter
Return Type
Promise<string>

[↑ Back to ask ↑]

autotext

ask.autotext(question: string | Breadcrumb, choices: ask.PromptChoice<T>[], initial: T | string, validate: (item: T, index: number, typedValue: string) => Error | string | boolean | void, lc: LineCounter): Promise<T>

Get a text input from the user, with auto-completion.

const name = await ask.autotext('What is your name?', ['Jack', 'Jane', 'Joe']); // 'Jack'
# Parameter Name Required Type
0 question Yes string | Breadcrumb
1 choices Yes ask.PromptChoice<T>[]
2 initial No T | string
3 validate No (item: T, index: number, typedValue: string) => Error | string | boolean | void
4 lc No LineCounter
Return Type
Promise<T>

[↑ Back to ask ↑]

number

ask.number(question: string | Breadcrumb, initial: number, validate: (value: number) => Error | string | boolean | void, lc: LineCounter): Promise<number>

Get a number input from the user.

const age = await ask.number('How old are you?'); // 30
# Parameter Name Required Type
0 question Yes string | Breadcrumb
1 initial No number
2 validate No (value: number) => Error | string | boolean | void
3 lc No LineCounter
Return Type
Promise<number>

[↑ Back to ask ↑]

boolean

ask.boolean(question: string | Breadcrumb, initial: boolean, validate: (value: boolean) => Error | string | boolean | void, lc: LineCounter): Promise<boolean>

Get a boolean input from the user (yes or no)

const isCool = await ask.boolean('Is this cool?'); // true
# Parameter Name Required Type Default
0 question Yes string | Breadcrumb
1 initial No boolean true
2 validate No (value: boolean) => Error | string | boolean | void
3 lc No LineCounter
Return Type
Promise<boolean>

[↑ Back to ask ↑]

booleanYN

ask.booleanYN(question: string | Breadcrumb, validate: (value: boolean) => Error | string | boolean | void, lc: LineCounter): Promise<boolean>

Get a boolean input from the user (yes or no)

Alternative interface to ask.boolean

const isCool = await ask.booleanYN('Is this cool?'); // true
# Parameter Name Required Type
0 question Yes string | Breadcrumb
1 validate No (value: boolean) => Error | string | boolean | void
2 lc No LineCounter
Return Type
Promise<boolean>

[↑ Back to ask ↑]

select

ask.select(question: string | Breadcrumb, choices: ask.PromptChoice<T>[], initial: ask.PromptChoice<T> | number, validate: (item: T, index: number) => Error | string | boolean | void, lc: LineCounter): Promise<T>

Get the user to select an option from a list.

const colour = await ask.select('Whats your favourite colour?', ['red', 'green', 'blue']); // 'red'
# Parameter Name Required Type
0 question Yes string | Breadcrumb
1 choices Yes ask.PromptChoice<T>[]
2 initial No ask.PromptChoice<T> | number
3 validate No (item: T, index: number) => Error | string | boolean | void
4 lc No LineCounter
Return Type
Promise<T>

[↑ Back to ask ↑]

multiselect

ask.multiselect(question: string | Breadcrumb, choices: ask.PromptChoice<T>[], initial: ask.PromptChoice<T> | ask.PromptChoice<T>[] | number | number[], validate: (items: T[], indexes: number[]) => Error | string | boolean | void, lc: LineCounter): Promise<T[]>

Get the user to select multiple opts from a list.

const colours = await ask.multiselect('Whats your favourite colours?', ['red', 'green', 'blue']); // ['red', 'green']
# Parameter Name Required Type
0 question Yes string | Breadcrumb
1 choices Yes ask.PromptChoice<T>[]
2 initial No ask.PromptChoice<T> | ask.PromptChoice<T>[] | number | number[]
3 validate No (items: T[], indexes: number[]) => Error | string | boolean | void
4 lc No LineCounter
Return Type
Promise<T[]>

[↑ Back to ask ↑]

date

ask.date(questionText: string | Breadcrumb, initial: Date, validate: (date: Date) => Error | string | boolean | void, lc: LineCounter): Promise<Date>

Get a date input from the user.

const date = await ask.date('Whats the date?');
// [Date: 2023-01-01T12:00:00.000Z] (user inputted date, always at 12 midday)
# Parameter Name Required Type
0 questionText No string | Breadcrumb
1 initial No Date
2 validate No (date: Date) => Error | string | boolean | void
3 lc No LineCounter
Return Type
Promise<Date>

[↑ Back to ask ↑]

time

ask.time(questionText: string | Breadcrumb, initial: Date, validate: (date: Date) => Error | string | boolean | void, lc: LineCounter): Promise<Date>

Get a time input from the user.

const time = await ask.time('Whats the time?');
// [Date: 2023-01-01T12:00:00.000Z] (user inputted time, with todays date)

const time2 = await ask.time('Whats the time?', new Date('1999-12-31'));
// [Date: 1999-12-31T12:00:00.000Z] (user inputted time, with same date as initial)
# Parameter Name Required Type
0 questionText No string | Breadcrumb
1 initial No Date
2 validate No (date: Date) => Error | string | boolean | void
3 lc No LineCounter
Return Type
Promise<Date>

[↑ Back to ask ↑]

datetime

ask.datetime(questionText: string | Breadcrumb, initial: Date, validate: (date: Date) => Error | string | boolean | void, lc: LineCounter): Promise<Date>

Get a date and time input from the user.

const when = await ask.datetime('Whats the date/time?');
// [Date: 2023-03-05T20:30:00.000Z] (user inputted time & date)
# Parameter Name Required Type
0 questionText No string | Breadcrumb
1 initial No Date
2 validate No (date: Date) => Error | string | boolean | void
3 lc No LineCounter
Return Type
Promise<Date>

[↑ Back to ask ↑]

dateRange

ask.dateRange(questionText: string | Breadcrumb, initialStart: Date, initialEnd: Date, validate: (dates: [Date, Date]) => Error | string | boolean | void, lc: LineCounter): Promise<[Date, Date]>

Get a date range input from the user.

const range = await ask.dateRange('When is the festival?');
// [
//   [Date: 2023-03-01T12:00:00.000Z],
//   [Date: 2023-03-31T12:00:00.000Z]
// ]
# Parameter Name Required Type
0 questionText No string | Breadcrumb
1 initialStart No Date
2 initialEnd No Date
3 validate No (dates: [Date, Date]) => Error | string | boolean | void
4 lc No LineCounter
Return Type
Promise<[Date, Date]>

[↑ Back to ask ↑]

fileExplorer

fileExplorer

ask.fileExplorer(questionText: string | Breadcrumb, selectType: 'd' | 'f', startPath: string, validate: (path: string) => Error | string | boolean | void, lc: LineCounter): Promise<string>

Get a file or folder path from the user.

const file = await ask.fileExplorer('What file?', 'f');
// '/Users/user/Documents/some_file.txt'

const dir = await ask.fileExplorer('What file?', 'd', '/Users/jackcannon/Documents');
// '/Users/jackcannon/Documents/some_folder'
# Parameter Name Required Type Default
0 questionText Yes string | Breadcrumb
1 selectType No 'd' | 'f' 'f'
2 startPath No string process.cwd()
3 validate No (path: string) => Error | string | boolean | void
4 lc No LineCounter
Return Type
Promise<string>

[↑ Back to ask ↑]

multiFileExplorer

ask.multiFileExplorer(questionText: string | Breadcrumb, selectType: 'd' | 'f', startPath: string, validate: (paths: string[]) => Error | string | boolean | void, lc: LineCounter): Promise<string[]>

Get multiple file or folder paths from the user.

const files = await ask.multiFileExplorer('What files?', 'f');
// [
//   '/Users/user/Documents/some_file_1.txt',
//   '/Users/user/Documents/some_file_2.txt',
//   '/Users/user/Documents/some_file_3.txt'
// ]
# Parameter Name Required Type Default
0 questionText Yes string | Breadcrumb
1 selectType No 'd' | 'f' 'f'
2 startPath No string process.cwd()
3 validate No (paths: string[]) => Error | string | boolean | void
4 lc No LineCounter
Return Type
Promise<string[]>

[↑ Back to ask ↑]

saveFileExplorer

ask.saveFileExplorer(questionText: string | Breadcrumb, startPath: string, suggestedFileName: string, validate: (dir: string, filename?: string) => Error | string | boolean | void): Promise<string>

Get a file path from the user, with the intention of saving a file to that path.

const HOME_DIR = '/Users/user/Documents';
const savePath = await ask.saveFileExplorer('Save file', HOME_DIR, 'data.json');
// '/Users/user/Documents/data.json'
# Parameter Name Required Type Default
0 questionText Yes string | Breadcrumb
1 startPath No string process.cwd()
2 suggestedFileName No string ''
3 validate No (dir: string, filename?: string) => Error | string | boolean | void
Return Type
Promise<string>

[↑ Back to ask ↑]

table

A collection of functions for asking questions with tables.

[↑ Back to ask ↑]

table.select

ask.table.select(question: string | Breadcrumb, items: T[], settings: AskTableDisplaySettings<T>, initial: T | number, validate: (item: T) => Error | string | boolean | void, lc: LineCounter): Promise<T>

Get a single selection from a table.

const items = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 26 },
  { name: 'Derek', age: 27 }
];
const headers = [['Name', 'Age']];
const itemToRow = ({ name, age }) => [name, age];

const answer = await ask.table.select('Who?', items, undefined, itemToRow, headers);
// ┏━━━┳━━━━━━━┳━━━━━┓
// ┃   ┃ Name  ┃ Age ┃
// ┡━━━╇━━━━━━━╇━━━━━┩
// │   │ John  │ 25  │
// ├───┼───────┼─────┤
// │ ❯ │ Jane  │ 26  │
// ├───┼───────┼─────┤
// │   │ Derek │ 27  │
// └───┴───────┴─────┘
// Returns: { name: 'Jane', age: 26 }
# Parameter Name Required Type Default
0 question Yes string | Breadcrumb
1 items Yes T[]
2 settings No AskTableDisplaySettings<T> {}
3 initial No T | number
4 validate No (item: T) => Error | string | boolean | void
5 lc No LineCounter
Return Type
Promise<T>

[↑ Back to ask ↑]

table.multiselect

ask.table.multiselect(question: string | Breadcrumb, items: T[], settings: AskTableDisplaySettings<T>, initial: T[] | number[], validate: (items: T[]) => Error | string | boolean | void, lc: LineCounter): Promise<T[]>

Get multiple selections from a table.

const items = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 26 },
  { name: 'Derek', age: 27 }
];
const headers = [['Name', 'Age']];
const itemToRow = ({ name, age }) => [name, age];

const answer = await ask.table.multiselect('Who?', items, undefined, itemToRow, headers);
┏━━━┳━━━━━━━┳━━━━━┓
    Name   Age 
┡━━━╇━━━━━━━╇━━━━━┩
   John   25  
├───┼───────┼─────┤
   Jane   26  
├───┼───────┼─────┤
   Derek  27  
└───┴───────┴─────┘
// [
//   { name: 'John', age: 25 },
//   { name: 'Derek', age: 27 }
// ]
# Parameter Name Required Type Default
0 question Yes string | Breadcrumb
1 items Yes T[]
2 settings No AskTableDisplaySettings<T> {}
3 initial No T[] | number[]
4 validate No (items: T[]) => Error | string | boolean | void
5 lc No LineCounter
Return Type
Promise<T[]>

[↑ Back to ask ↑]

AskTableDisplaySettings

AskTableDisplaySettings<T>;

Settings for how the table should display the items

All settings are optional.

Name Type Description
rows any[][] | (item: T) => any[] Rows to display or function that takes an item and returns a row
headers any[][] | RemapOf<T, string> Header to display, or object with title for each item property
options table.TableOptions Options object for table (some options are overridden)

[↑ Back to ask ↑]

trim

ask.trim(question: string | Breadcrumb, totalFrames: number, frameRate: number, initial: Partial<Handles<number>>, validate: (handles: Handles<number>) => Error | string | boolean | void, lc: LineCounter): Promise<Handles<number>>

Get a start and end frame from the user

# Parameter Name Required Type Default
0 question Yes string | Breadcrumb
1 totalFrames Yes number
2 frameRate No number 60
3 initial No Partial<Handles<number>>
4 validate No (handles: Handles<number>) => Error | string | boolean | void
5 lc No LineCounter
Return Type
Promise<Handles<number>>

[↑ Back to ask ↑]

Extra

These are ask functions that don't prompt the user, but can help manage or organise how you use prompts

[↑ Back to ask ↑]

customise

ask.customise(options: Partial<ask.AskOptions>): void

Customise the behaviour/appearance of the ask prompts.

See ask.AskOptions for the options available.

ask.customise({ general: { themeColour: 'magenta' } }); // change the theme colour to magenta
ask.customise({ general: { lc } }); // set a line counter for that all prompts will add to when complete
ask.customise({ formatters: { formatPrompt: 'fullBox' } }); // change the format of the prompt
# Parameter Name Required Type
0 options Yes Partial<ask.AskOptions>
Return Type
void

[↑ Back to ask ↑]

loading

ask.loading(question: string | Breadcrumb, isComplete: boolean, isError: boolean, lc: LineCounter): { stop: () => void; }

Display an animated loading indicator that imitates the display of a prompt

Intended to be indicate a question is coming, but something is loading first. For general 'loading' indicators, use out.loading.

const loader = ask.loading('What is your name?');
// ...
loader.stop();
# Parameter Name Required Type Default
0 question Yes string | Breadcrumb
1 isComplete No boolean false
2 isError No boolean false
3 lc No LineCounter
Return Type
{ stop: () => void; }

[↑ Back to ask ↑]

countdown

ask.countdown(totalSeconds: number, template: (s: second) => string, isComplete: boolean, isError: boolean): Promise<void>

Animated countdown for a given number of seconds

await ask.countdown(5);
# Parameter Name Required Type
0 totalSeconds Yes number
1 template No (s: second) => string
2 isComplete No boolean
3 isError No boolean
Return Type
Promise<void>

[↑ Back to ask ↑]

pause

ask.pause(text: string | Breadcrumb): Promise<void>

Pause the program until the user presses enter

await ask.pause();
# Parameter Name Required Type Default
0 text No string | Breadcrumb 'Press enter to continue...'
Return Type
Promise<void>

[↑ Back to ask ↑]

imitate

ask.imitate(question: string | Breadcrumb, result: any, isComplete: boolean, isError: boolean, errorMessage: string, lc: LineCounter): void

Imitate the display of a prompt

imitate('What is your name?', 'Jack', true);

ask.imitate('What is your name?', 'Jack', true);
# Parameter Name Required Type Default
0 question Yes string | Breadcrumb
1 result No any
2 isComplete No boolean true
3 isError No boolean false
4 errorMessage No string
5 lc No LineCounter
Return Type
void

[↑ Back to ask ↑]

prefill

ask.prefill(question: string | Breadcrumb, value: T | undefined, askFn: (question: string | Breadcrumb, lc: LineCounter) => Promise<T> | T, lc: LineCounter): Promise<T>

Auto-fills an ask prompt with the provided value, if defined.

Continues to display the 'prompt', but already 'submitted'

Good for keeping skipping parts of forms, but providing context and keeping display consistent

let data = {};
const name1 = ask.prefill(data.name, 'What is your name?', ask.text); // User input

data = {name: 'Jack'}
const name2 = ask.prefill(data.name, 'What is your name?', ask.text); // Jack
# Parameter Name Required Type
0 question Yes string | Breadcrumb
1 value Yes T | undefined
2 askFn Yes (question: string | Breadcrumb, lc: LineCounter) => Promise<T> | T
3 lc No LineCounter
Return Type
Promise<T>

[↑ Back to ask ↑]

wizard

ask.wizard(startObj: Partial<T>): ask.Wizard<T>

Create a wizard object that can be used to build up a complex object

interface Example {
  foo: string;
  bar: number;
  baz: string;
}

const base: Partial<Example> = {
  baz: 'baz'
};

const wiz = ask.wizard<Example>(base);

await wiz.add('foo', ask.text('What is foo?')); // User input: foo

await wiz.add('bar', ask.number('What is bar?')); // User input: 123

const result = wiz.get(); // { baz: 'baz', foo: 'foo', bar: 123 }
# Parameter Name Required Type Default
0 startObj No Partial<T> {}
Return Type
ask.Wizard<T>

[↑ Back to ask ↑]

menu

ask.menu(question: string | Breadcrumb, items: MenuItem<T>[], initial: MenuItem<T> | T | number, validate: (value: T, index: number) => Error | string | boolean | void, lc: LineCounter): Promise<T>

Wrapper for ask.select that styles the output as a menu, with icons and colours

const menuItems: ask.MenuItem<string>[] = [
  { value: 'done', title: colr.dim(`[ Finished ]`), icon: '✔', colour: colr.dark.green.bold },
  { value: 'create', title: `${colr.bold('Create')} a new thing`, icon: '+', colour: colr.black.greenBg },
  { value: 'duplicate', title: `${colr.bold('Duplicate')} a thing`, icon: '⌥', colour: colr.black.cyanBg },
  { value: 'edit', title: `${colr.bold('Edit')} a thing`, icon: '↻', colour: colr.black.yellowBg },
  { value: 'delete', title: `${colr.bold('Remove')} thing(s)`, icon: '×', colour: colr.black.redBg },
  { value: 'delete-all', title: colr.bold(`Remove all`), icon: '✖', colour: colr.black.darkBg.redBg }
];

const result = await ask.menu('Pick a menu item', menuItems, 'edit'); // 'duplicate' (or other value)
# Parameter Name Required Type
0 question Yes string | Breadcrumb
1 items Yes MenuItem<T>[]
2 initial No MenuItem<T> | T | number
3 validate No (value: T, index: number) => Error | string | boolean | void
4 lc No LineCounter
Return Type
Promise<T>

[↑ Back to ask ↑]

section

ask.section(question: string | Breadcrumb, sectionHeader: (lc: LineCounter) => void | Promise<any>, ...questionFns: [...T][]): Promise<TupleFromQuestionFuncs<T>>

Allows information to be displayed before a question, and follow up questions to be asked, while only leaving the 'footprint' of a single question afterwards.

const ans1 = await ask.text('Question 1:');
const ans2 = await ask.section('Question 2:',
  (lc: LineCounter) => {
    lc.log('Some information');
  },
  (qst) => ask.text(qst),
  () => ask.text('Question 2b:')
);

During the section, it looks like this:

Question 1: answer1
┄┄┄┄┄◦┄┄┄┄┄┄┄◦┄┄┄┄┄┄┄◦┄┄┄┄┄┄┄◦┄┄┄┄┄┄
Some information
┄┄┄┄┄◦┄┄┄┄┄┄┄◦┄┄┄┄┄┄┄◦┄┄┄┄┄┄┄◦┄┄┄┄┄┄
Question 2: answer2
Question 2b: answer2b

After the last question in the section has been submitted, it looks like this:

Question 1: answer1
Question 2a: [ answer2, answer2b ]
# Parameter Name Required Type
0 question Yes string | Breadcrumb
1 sectionHeader No (lc: LineCounter) => void | Promise<any>
2… questionFns No [...T][]
Return Type
Promise<TupleFromQuestionFuncs<T>>

[↑ Back to ask ↑]

separator

ask.separator(version: 'down' | 'none' | 'up', spacing: number, offset: number, width: number, lc: LineCounter): void

Prints a separator line to the console.

ask.separator('down');
// ┄┄┄┄┄▿┄┄┄┄┄┄┄▿┄┄┄┄┄┄┄▿┄┄┄┄┄┄┄▿┄┄┄┄┄┄┄▿┄┄┄┄┄┄┄▿┄┄┄┄┄┄

ask.separator('none', 15);
// ┄┄┄┄┄┄┄┄┄┄◦┄┄┄┄┄┄┄┄┄┄┄┄┄┄◦┄┄┄┄┄┄┄┄┄┄┄┄┄┄◦┄┄┄┄┄┄┄┄┄┄┄

ask.separator('up', 5, 2);
// ┄┄┄┄┄┄┄┄▵┄┄┄┄▵┄┄┄┄▵┄┄┄┄▵┄┄┄┄▵┄┄┄┄▵┄┄┄┄▵┄┄┄┄▵┄┄┄┄┄┄┄┄
# Parameter Name Required Type Default
0 version No 'down' | 'none' | 'up' 'down'
1 spacing No number 8
2 offset No number 0
3 width No number out.utils.getTerminalWidth() - 2
4 lc No LineCounter
Return Type
void

[↑ Back to ask ↑]

utils

itemsToPromptObjects

ask.utils.itemsToPromptObjects(items: T[], titles: string[], titleFn: TitleFn<T>): { title: string; value: T; }[]

Take an array of items and convert them to an array of prompt objects

ask.utils.itemsToPromptObjects(['lorem', 'ipsum', 'dolor'])
// [
//   { title: 'lorem', value: 'lorem' },
//   { title: 'ipsum', value: 'ipsum' },
//   { title: 'dolor', value: 'dolor' }
// ]

ask.utils.itemsToPromptObjects(['lorem', 'ipsum', 'dolor'], ['Lorem', 'Ipsum', 'Dolor'])
// [
//   { title: 'Lorem', value: 'lorem' },
//   { title: 'Ipsum', value: 'ipsum' },
//   { title: 'Dolor', value: 'dolor' }
// ]

ask.utils.itemsToPromptObjects(['lorem', 'ipsum', 'dolor'], undefined, (s) => s.toUpperCase())
// [
//   { title: 'LOREM', value: 'lorem' },
//   { title: 'IPSUM', value: 'ipsum' },
//   { title: 'DOLOR', value: 'dolor' }
// ]
# Parameter Name Required Type Default
0 items Yes T[]
1 titles No string[] []
2 titleFn No TitleFn<T>
Return Type
{ title: string; value: T; }[]

[↑ Back to ask ↑]

AskOptions

ask.AskOptions;

Options to customise the behaviour/appearance of the ask prompts.

Use with ask.customise to set these options.

[↑ Back to ask ↑]

general Options

ask.AskOptions.general;

General options for customising ask prompts

Name Type Description
themeColour string (Colour) Set the main theme colour
lc LineCounter A line counter that all ask prompts will add to when complete
boxType 'thin' | 'thick' What type of box drawing lines to use
beeps boolean Whether to make an audio beeps when appropriate
maxItemsOnScreen number How many select/multiselect items to have on screen at most
scrollMargin number How much space to leaving when 'scrolling' lists of items
fileExplorerColumnWidth number How wide to make each panel of the fileExplorer interface
fileExplorerMaxItems number How many items to show in each panel of the fileExplorer interface
tableSelectMaxHeightPercentage number Percent of terminal height to use at max for table selects
timelineSpeed number How many frames to move on a timeline at a time
timelineFastSpeed number How many frames to move on a timeline at a time (fast mode)

[↑ Back to AskOptions ↑]

text Options

ask.AskOptions.text;

English natural-language elements that you may wish to localise

Name Type Description
boolTrueKeys string What buttons to use to indicate true for boolean prompts
boolFalseKeys string What buttons to use to indicate false for boolean prompts
boolYes string 'Yes'
boolNo string 'No'
boolYesNoSeparator string '/'
boolYN string '(Y/n)'
selectAll string '[Select All]'
done string 'done'
items (num: number) => string '[X items]'
countdown (secs: number) => string 'Starting in Xs...'
file string 'File'
directory string 'Directory'
loading string 'Loading...'
selected (num: number) => string 'X selected'
specialNewFolderEnterNothingCancel string 'Enter nothing to cancel'
specialNewFolderAddingFolderTo string 'Adding folder to '
specialNewFolderQuestion (hl: any) => string 'What do you want to name the new folder?'
specialSaveFileSavingFileTo string 'Saving file to '
specialSaveFileQuestion (hl: any) => string 'What do you want to name the file?'

[↑ Back to AskOptions ↑]

formatters Options

ask.AskOptions.formatters;

Functions for formatting how the prompts should display

[↑ Back to AskOptions ↑]

formatPrompt
ask.AskOptions.formatters.formatPrompt;

How to format the prompts

Presets: oneLine, halfBox, halfBoxClosed, fullBox, fullBoxClosed

Type:

(
  question: string | Breadcrumb,
  value: string,
  items: string | undefined,
  errorMessage: string | undefined,
  theme: AskOptionsForState,
  isComplete: boolean,
  isExit: boolean
) => string;

[↑ Back to `formatters` Options ↑]

formatItems
ask.AskOptions.formatters.formatItems;

How to format lists of items

Presets: block, blockAlt, simple, simpleAlt

Type:

<T extends unknown>(
  allItems: PromptChoiceFull<T>[],
  scrolledItems: ScrolledItems<PromptChoiceFull<T>>,
  selected: number[] | undefined,
  type: 'single' | 'multi',
  theme: AskOptionsForState,
  isExit: boolean
) => string;

[↑ Back to `formatters` Options ↑]

colours Options

ask.AskOptions.colours;

Colours for all the different elements

All colours can be a single WrapFn value, or a set of WrapFn values, one for each state (normal, error, done) When single value, it is used for all states. When only a few states are set, the others will remain unchanged.

Name Description
decoration General decoration and cosmetics
questionText The text of the question of the prompt
specialIcon Special icon for the 'state'
openingIcon The initial/opening icon
promptIcon The icon that indicates where you are typing
result General result
resultText String results
resultNumber Number results
resultBoolean Boolean results
resultArray Array results
resultDate Date results
loadingIcon Icon for ask.loading
errorMsg The error message (if there is one)
item A normal item in a list
itemIcon Icon for a normal item in a list
itemHover A hovered item in a list
itemHoverIcon Icon for a hovered item in a list
itemBlockHover A hovered item in a list (block mode)
itemBlockHoverIcon Icon for a hovered item in a list (block mode)
itemSelected A selected item in a list
itemSelectedIcon Icon for a selected item in a list
itemUnselected An unselected item in a list
itemUnselectedIcon Icon for an unselected item in a list
scrollbarTrack The track for the scrollbar
scrollbarBar The bar for the scrollbar
selectAllText 'Select All' item in a multi-select
boolYNText The '(Y/n)' bit for the booleanYN prompt
countdown ask.countdown
pause ask.pause
specialHover The focus of what the user is controlling (for dates, fileExplorer, etc)
specialSelected Something that has been selected (for dates, fileExplorer, etc)
specialHighlight More important that normal (e.g. date within a range) (for dates, fileExplorer, etc)
specialNormal Normal items (for dates, fileExplorer, etc)
specialFaded Not important (for dates, fileExplorer, etc)
specialHint Hints/tips/advice (for dates, fileExplorer, etc)
specialInactiveHover The focus of what the user is controlling (Inactive) (for dates, fileExplorer, etc)
specialInactiveSelected Something that has been selected (Inactive) (for dates, fileExplorer, etc)
specialInactiveHighlight More important that normal (e.g. date within a range) (Inactive) (for dates, fileExplorer, etc)
specialInactiveNormal Normal items (Inactive) (for dates, fileExplorer, etc)
specialInactiveFaded Not important (Inactive) (for dates, fileExplorer, etc)
specialInactiveHint Hints/tips/advice (Inactive) (for dates, fileExplorer, etc)
specialInfo Action bar at bottom (for dates, fileExplorer, etc)
specialErrorMsg Error messages (for dates, fileExplorer, etc)
specialErrorIcon Icon for errors (for dates, fileExplorer, etc)
tableSelectHover Hover for table selects only (shouldn't be 'block'/bg styles)
timelineTrack The (inactive) track of a timeline
timelineTrackActive The active track of a timeline
timelineHandle The (inactive) control handle on a timeline
timelineHandleActive The active control handle on a timeline

[↑ Back to AskOptions ↑]

symbols Options

ask.AskOptions.symbols;

Variety of symbols and 'icons' for different aspects of the display

All symbols can be a single string value, or a set of string values, one for each state (normal, error, done) When single value, it is used for all states. When only a few states are set, the others will remain unchanged.

Name Description
specialIcon Special icon for the 'state'
openingIcon The initial/opening icon
promptIcon The icon that indicates where you are typing
errorMsgPrefix Icon shown before error messages
itemIcon Icon for a normal item in a list
itemHoverIcon Icon for a hovered item in a list
itemSelectedIcon Icon for a selected item in a list
itemUnselectedIcon Icon for an unselected item in a list
scrollUpIcon Used to indicate you can scroll up
scrollDownIcon Used to indicate you can scroll down
scrollbarTrack The track part of the scrollbar
scrollbarTrackTrimTop The trimmed top of the track (half height)
scrollbarTrackTrimBottom The trimmed bottom of the track (half height)
scrollbarBar The bar part of the scrollbar
scrollbarBarTrimTop The trimmed top of the bar (half height)
scrollbarBarTrimBottom The trimmed bottom of the bar (half height)
separatorLine Line added by ask.separator
separatorNodeDown Node is ask.separator line that indicates 'down'
separatorNodeNone Node is ask.separator line that breaks up the pattern
separatorNodeUp Node is ask.separator line that indicates 'up'
specialErrorIcon Icon for errors (for dates, fileExplorer, etc)
folderOpenableIcon Shown at end of line for folders to show they can be opened (right-wards)
fileOpenableIcon File version of folderOpenableIcon. Typically empty
timelineTrack The track of a timeline
timelineHandle The control handle on a timeline
timelineBar The 'bar' (active portion) of a timeline

[↑ Back to AskOptions ↑]

PromptChoice

ask.PromptChoice<T>;

A choice for a prompt

Equivalent to T | { title?: string; value?: T; selected?: boolean; }

[↑ Back to ask ↑]

out

A collection of functions to print to the console

[↑ Back to top ↑]

getWidth

out.getWidth(text: string): number

A rough approximation of the width of the given text (as it would appear in the terminal)

Removes all ansi escape codes, and attempts to count emojis as 2 characters wide

Note: Many special characters may not be counted correctly. Emoji support is also not perfect.

out.getWidth('FOO BAR'); // 7
out.getWidth('↓←→↑'); // 4
out.getWidth(colr.red('this is red')); // 11
# Parameter Name Required Type
0 text Yes string
Return Type
number

[↑ Back to out ↑]

pad

out.pad(line: string, start: number, end: number, replaceChar: string): string

Pad before and after the given text with the given character.

pad('foo', 3, 1, '-'); // '---foo-'
pad('bar', 10, 5, '_'); // '__________bar_____'
# Parameter Name Required Type Default
0 line Yes string
1 start Yes number
2 end Yes number
3 replaceChar No string ' '
Return Type
string

[↑ Back to out ↑]

center

out.center(item: any, width: number, replaceChar: string, forceWidth: boolean): string

Align the given text to the center within the given width of characters/columns

Giving a width of 0 will use the terminal width

out.center('foo', 10); // '   foo    '
out.center('something long', 10); // 'something long'
out.center('lines\n1\n2', 5);
// 'lines' + '\n' +
// '  1  ' + '\n' +
// '  2  '
# Parameter Name Required Type Default
0 item Yes any
1 width No number out.utils.getTerminalWidth()
2 replaceChar No string ' '
3 forceWidth No boolean true
Return Type
string

[↑ Back to out ↑]

left

out.left(item: any, width: number, replaceChar: string, forceWidth: boolean): string

Align the given text to the left within the given width of characters/columns

Giving a width of 0 will use the terminal width

out.left('foo', 10); // 'foo       '
out.left('something long', 10); // 'something long'
out.left('lines\n1\n2', 5);
// 'lines' + '\n' +
// '1    ' + '\n' +
// '2    '
# Parameter Name Required Type Default
0 item Yes any
1 width No number out.utils.getTerminalWidth()
2 replaceChar No string ' '
3 forceWidth No boolean true
Return Type
string

[↑ Back to out ↑]

right

out.right(item: any, width: number, replaceChar: string, forceWidth: boolean): string

Align the given text to the right within the given width of characters/columns

Giving a width of 0 will use the terminal width

out.right('foo', 10); // '       foo'
out.right('something long', 10); // 'something long'
out.right('lines\n1\n2', 5);
// 'lines' + '\n' +
// '    1' + '\n' +
// '    2'
# Parameter Name Required Type Default
0 item Yes any
1 width No number out.utils.getTerminalWidth()
2 replaceChar No string ' '
3 forceWidth No boolean true
Return Type
string

[↑ Back to out ↑]

justify

out.justify(item: any, width: number, replaceChar: string, forceWidth: boolean): string

Evenly space the text horizontally across the given width.

Giving a width of 0 will use the terminal width

const lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit';
out.justify(out.wrap(lorem, 20), 20);
// 'Lorem  ipsum   dolor' + '\n' +
// 'sit            amet,' + '\n' +
// 'consectetur         ' + '\n' +
// 'adipiscing      elit'
# Parameter Name Required Type Default
0 item Yes any
1 width No number out.utils.getTerminalWidth()
2 replaceChar No string ' '
3 forceWidth No boolean true
Return Type
string

[↑ Back to out ↑]

leftLines

out.leftLines(lines: string[], width: number): string[]

Align each line of the given text to the left within the given width of characters/columns

out.leftLines(['This is line 1', 'This is a longer line 2', 'Line 3']);
// [
//   'This is line 1         ',
//   'This is a longer line 2',
//   'Line 3                 '
// ]
# Parameter Name Required Type Default
0 lines Yes string[]
1 width No number getLongestLen(lines)
Return Type
string[]

[↑ Back to out ↑]

centerLines

out.centerLines(lines: string[], width: number): string[]

Align each line of the given text to the center within the given width of characters/columns

out.rightLines(['This is line 1', 'This is a longer line 2', 'Line 3']);
// [
//   '         This is line 1',
//   'This is a longer line 2',
//   '                 Line 3'
// ]
# Parameter Name Required Type Default
0 lines Yes string[]
1 width No number getLongestLen(lines)
Return Type
string[]

[↑ Back to out ↑]

rightLines

out.rightLines(lines: string[], width: number): string[]

Align each line of the given text to the right within the given width of characters/columns

out.centerLines(['This is line 1', 'This is a longer line 2', 'Line 3']);
// [
//   '    This is line 1     ',
//   'This is a longer line 2',
//   '        Line 3         '
// ]
# Parameter Name Required Type Default
0 lines Yes string[]
1 width No number getLongestLen(lines)
Return Type
string[]

[↑ Back to out ↑]

justifyLines

out.justifyLines(lines: string[], width: number): string[]

Justify align each line of the given text within the given width of characters/columns

out.justifyLines(['This is line 1', 'This is a longer line 2', 'Line 3']);
// [
//   'This    is    line    1',
//   'This is a longer line 2',
//   'Line                  3'
// ]
# Parameter Name Required Type Default
0 lines Yes string[]
1 width No number getLongestLen(lines)
Return Type
string[]

[↑ Back to out ↑]

align

out.align(item: any, direction: AlignType, width: number, replaceChar: string, forceWidth: boolean): string

Align the given text to the given alignment within the given width of characters/columns

Giving a width of 0 will use the terminal width

out.align('foo', 'left', 10); // 'foo       '
out.align('something long', 'center', 10); // 'something long'
out.align('lines\n1\n2', 'right', 5);
// 'lines' + '\n' +
// '    1' + '\n' +
// '    2'
# Parameter Name Required Type Default
0 item Yes any
1 direction Yes AlignType
2 width No number out.utils.getTerminalWidth()
3 replaceChar No string ' '
4 forceWidth No boolean true
Return Type
string

[↑ Back to out ↑]

split

out.split(leftItem: any, rightItem: any, width: number, replaceChar: string): string

Split the given text into two parts, left and right, with the given width of characters/columns

out.split('Left', 'Right', 15); // Left      Right
# Parameter Name Required Type Default
0 leftItem Yes any
1 rightItem Yes any
2 width No number out.utils.getTerminalWidth()
3 replaceChar No string ' '
Return Type
string

[↑ Back to out ↑]

wrap

out.wrap(item: any, width: number, alignment: AlignType, forceWidth: boolean): string

Wrap the given text to the given width of characters/columns

wrap('This is a sentence', 15);
// 'This is' + '\n' +
// 'a sentence'
# Parameter Name Required Type Default
0 item Yes any
1 width No number out.utils.getTerminalWidth()
2 alignment No AlignType
3 forceWidth No boolean false
Return Type
string

[↑ Back to out ↑]

moveUp

out.moveUp(lines: number): void

Move the terminal cursor up X lines, clearing each row.

Useful for replacing previous lines of output

moveUp(1);
# Parameter Name Required Type Default
0 lines No number 1
Return Type
void

[↑ Back to out ↑]

loading

out.loading(action: (s: string) => string | void, lines: number, symbols: string[]): { stop: () => void; }

Display an animated loading indicator

If the given action returns a string, it will be printed. Otherwise, it will assume the action prints to output itself (and clears the number of lines given as the second argument)

const loader = out.loading();
// ...
loader.stop();
# Parameter Name Required Type Default
0 action No (s: string) => string | void loadingDefault
1 lines No number 1
2 symbols No string[] loadingChars
Return Type
{ stop: () => void; }

[↑ Back to out ↑]

limitToLength

out.limitToLength(text: string, maxLength: number): string

Limit the length of a string to the given length

out.limitToLength('This is a very long sentence', 12); // 'This is a ve'
# Parameter Name Required Type
0 text Yes string
1 maxLength Yes number
Return Type
string

[↑ Back to out ↑]

limitToLengthStart

out.limitToLengthStart(text: string, maxLength: number): string

Limit the length of a string to the given length, keeping the end

out.limitToLengthStart('This is a very long sentence', 12); // 'ong sentence'
# Parameter Name Required Type
0 text Yes string
1 maxLength Yes number
Return Type
string

[↑ Back to out ↑]

truncate

out.truncate(text: string, maxLength: number, suffix: string): string

Limit the length of a string to the given length, and add an ellipsis if necessary

out.truncate('This is a very long sentence', 15); // 'This is a ve...'
# Parameter Name Required Type Default
0 text Yes string
1 maxLength No number out.utils.getTerminalWidth()
2 suffix No string colr.dim('…')
Return Type
string

[↑ Back to out ↑]

truncateStart

out.truncateStart(text: string, maxLength: number, suffix: string): string

Limit the length of a string to the given length, and add an ellipsis if necessary, keeping the end

out.truncateStart('This is a very long sentence', 15); // '...ong sentence'
# Parameter Name Required Type Default
0 text Yes string
1 maxLength No number out.utils.getTerminalWidth()
2 suffix No string colr.dim('…')
Return Type
string

[↑ Back to out ↑]

concatLineGroups

out.concatLineGroups(...groups: string[][]): any

Concatenate multiple line groups, aligning them by the longest line

out.concatLineGroups(['lorem', 'ipsum'], ['dolor', 'sit', 'amet']);
// [ 'loremdolor', 'ipsumsit  ', '     amet ' ]
# Parameter Name Required Type
0… groups No string[][]
Return Type
any

[↑ Back to out ↑]

getResponsiveValue

out.getResponsiveValue(options: ResponsiveOption<T>[]): T

Get a value based on the terminal width

out.getResponsiveValue([
  {minColumns: 0, value: 'a'},
  {minColumns: 10, value: 'b'},
  {minColumns: 100, value: 'c'},
  {minColumns: 1000, value: 'd'}
]) // c
# Parameter Name Required Type
0 options Yes ResponsiveOption<T>[]
Return Type
T

[↑ Back to out ↑]

ResponsiveOption

out.ResponsiveOption;

Configuration for a responsive value (see getResponsiveValue)

See getResponsiveValue for an example

[↑ Back to getResponsiveValue ↑]

ansi

ansi;
out.ansi;

ANSI escape codes for terminal manipulation

[↑ Back to out ↑]

cursor

ANSI escape codes for controlling the cursor in the terminal

[↑ Back to ansi ↑]

to
ansi.cursor.to(x: number, y: number): string
out.ansi.cursor.to(x: number, y: number): string

Move the cursor to a specific position

process.stdout.write(ansi.cursor.to(5, 10)); // moves the cursor
# Parameter Name Required Type Default Description
0 x No number 0 The x position to move the cursor to
1 y No number 0 The y position to move the cursor to
Return Type
string escape codes

[↑ Back to ansi ↑]

move
ansi.cursor.move(x: number, y: number): string
out.ansi.cursor.move(x: number, y: number): string

Move the cursor a specific amount of spaces

process.stdout.write(ansi.cursor.move(5, 10)); // moves the cursor down 5 lines and right 10 spaces
process.stdout.write(ansi.cursor.move(-5, -10)); // moves the cursor up 5 lines and left 10 spaces
# Parameter Name Required Type Default Description
0 x No number 0 How many spaces to move the cursor horizontally (negative values move left)
1 y No number 0 How many spaces to move the cursor vertically (negative values move up)
Return Type
string escape codes

[↑ Back to ansi ↑]

up
ansi.cursor.up(count: number): string
out.ansi.cursor.up(count: number): string

Move the cursor up a specific amount of spaces

process.stdout.write(ansi.cursor.up(5)); // moves the cursor up 5 lines
process.stdout.write(ansi.cursor.up(-5)); // moves the cursor down 5 lines
# Parameter Name Required Type Default Description
0 count No number 1 How many spaces to move the cursor up
Return Type
string escape codes

[↑ Back to ansi ↑]

down
ansi.cursor.down(count: number): string
out.ansi.cursor.down(count: number): string

Move the cursor down a specific amount of spaces

process.stdout.write(ansi.cursor.down(5)); // moves the cursor down 5 lines
process.stdout.write(ansi.cursor.down(-5)); // moves the cursor up 5 lines
# Parameter Name Required Type Default Description
0 count No number 1 How many spaces to move the cursor down
Return Type
string escape codes

[↑ Back to ansi ↑]

left
ansi.cursor.left(count: number): string
out.ansi.cursor.left(count: number): string

Move the cursor left (backward) a specific amount of spaces

process.stdout.write(ansi.cursor.left(5)); // moves the cursor left 5 spaces
process.stdout.write(ansi.cursor.left(-5)); // moves the cursor right 5 spaces
# Parameter Name Required Type Default Description
0 count No number 1 How many spaces to move the cursor left
Return Type
string escape codes

[↑ Back to ansi ↑]

right
ansi.cursor.right(count: number): string
out.ansi.cursor.right(count: number): string

Move the cursor right (forward) a specific amount of spaces

process.stdout.write(ansi.cursor.right(5)); // moves the cursor right 5 spaces
process.stdout.write(ansi.cursor.right(-5)); // moves the cursor left 5 spaces
# Parameter Name Required Type Default Description
0 count No number 1 How many spaces to move the cursor right
Return Type
string escape codes

[↑ Back to ansi ↑]

nextLine
ansi.cursor.nextLine(count: number): string
out.ansi.cursor.nextLine(count: number): string

Move the cursor to the beginning of the next line

process.stdout.write(ansi.cursor.nextLine()); // moves the cursor to the beginning of the next line
process.stdout.write(ansi.cursor.nextLine(5)); // moves the cursor down 5 lines and to the beginning of the next line
# Parameter Name Required Type Default Description
0 count No number 1 How many lines to move the cursor down
Return Type
string escape codes

[↑ Back to ansi ↑]

prevLine
ansi.cursor.prevLine(count: number): string
out.ansi.cursor.prevLine(count: number): string

Move the cursor to the beginning of the previous line

process.stdout.write(ansi.cursor.prevLine()); // moves the cursor to the beginning of the previous line
process.stdout.write(ansi.cursor.prevLine(5)); // moves the cursor up 5 lines and to the beginning of the previous line
# Parameter Name Required Type Default Description
0 count No number 1 How many lines to move the cursor up
Return Type
string escape codes

[↑ Back to ansi ↑]

lineStart
ansi.cursor.lineStart;
out.ansi.cursor.lineStart;

ANSI escape code to move the cursor to the beginning of the current line

process.stdout.write(ansi.cursor.lineStart); // moves the cursor to the beginning of the current line

[↑ Back to ansi ↑]

setShow
ansi.cursor.setShow(isShow: boolean): string
out.ansi.cursor.setShow(isShow: boolean): string

Set whether or not the cursor is shown

process.stdout.write(ansi.cursor.setShow(true)); // shows the cursor
process.stdout.write(ansi.cursor.setShow(false)); // hides the cursor
# Parameter Name Required Type Description
0 isShow Yes boolean Whether or not the cursor should be shown
Return Type
string escape code

[↑ Back to ansi ↑]

show
ansi.cursor.show;
out.ansi.cursor.show;

ANSI escape code to show the cursor

process.stdout.write(ansi.cursor.show); // shows the cursor

[↑ Back to ansi ↑]

hide
ansi.cursor.hide;
out.ansi.cursor.hide;

ANSI escape code to hide the cursor

process.stdout.write(ansi.cursor.hide); // hides the cursor

[↑ Back to ansi ↑]

save
ansi.cursor.save;
out.ansi.cursor.save;

ANSI escape code to save the current cursor position (can be restored with cursor.restore)

process.stdout.write(ansi.cursor.save); // saves the current cursor position
// ...
process.stdout.write(ansi.cursor.restore); // restores the saved cursor position

[↑ Back to ansi ↑]

restore
ansi.cursor.restore;
out.ansi.cursor.restore;

ANSI escape code to restore a previously saved cursor position (saved with cursor.save)

process.stdout.write(ansi.cursor.save); // saves the current cursor position
// ...
process.stdout.write(ansi.cursor.restore); // restores the saved cursor position

[↑ Back to ansi ↑]

scroll

ANSI escape codes for scrolling the terminal

[↑ Back to ansi ↑]

up
ansi.scroll.up(count: number): string
out.ansi.scroll.up(count: number): string

Scroll the terminal up a specific amount

process.stdout.write(ansi.scroll.up(5)); // scrolls the terminal up 5 lines
process.stdout.write(ansi.scroll.up(-5)); // scrolls the terminal down 5 lines
# Parameter Name Required Type Default Description
0 count No number 1 How much to scroll the terminal up by
Return Type
string escape codes

[↑ Back to ansi ↑]

down
ansi.scroll.down(count: number): string
out.ansi.scroll.down(count: number): string

Scroll the terminal down a specific amount

process.stdout.write(ansi.scroll.down(5)); // scrolls the terminal down 5 lines
process.stdout.write(ansi.scroll.down(-5)); // scrolls the terminal up 5 lines
# Parameter Name Required Type Default Description
0 count No number 1 How much to scroll the terminal down by
Return Type
string escape codes

[↑ Back to ansi ↑]

erase

ANSI escape codes for erasing parts of the terminal

[↑ Back to ansi ↑]

screen
ansi.erase.screen;
out.ansi.erase.screen;

ANSI escape code to erase the entire terminal screen

process.stdout.write(ansi.erase.screen); // erases the entire terminal screen

[↑ Back to ansi ↑]

up
ansi.erase.up(count: number): string
out.ansi.erase.up(count: number): string

Erase the terminal above the cursor

process.stdout.write(ansi.erase.up(5)); // erases the terminal above the cursor by 5 lines
process.stdout.write(ansi.erase.up(-5)); // erases the terminal below the cursor by 5 lines
# Parameter Name Required Type Default Description
0 count No number 1 How many lines to erase
Return Type
string escape codes

[↑ Back to ansi ↑]

down
ansi.erase.down(count: number): string
out.ansi.erase.down(count: number): string

Erase the terminal below the cursor

process.stdout.write(ansi.erase.down(5)); // erases the terminal below the cursor by 5 lines
process.stdout.write(ansi.erase.down(-5)); // erases the terminal above the cursor by 5 lines
# Parameter Name Required Type Default Description
0 count No number 1 How many lines to erase
Return Type
string escape codes

[↑ Back to ansi ↑]

line
ansi.erase.line;
out.ansi.erase.line;

ANSI escape code to erase the current line

process.stdout.write(ansi.erase.line); // erases the current line

[↑ Back to ansi ↑]

lineEnd
ansi.erase.lineEnd;
out.ansi.erase.lineEnd;

ANSI escape code to erase the current line from the cursor to the end

process.stdout.write(ansi.erase.lineEnd); // erases the current line from the cursor to the end

[↑ Back to ansi ↑]

lineStart
ansi.erase.lineStart;
out.ansi.erase.lineStart;

ANSI escape code to erase the current line from the cursor to the start

process.stdout.write(ansi.erase.lineStart); // erases the current line from the cursor to the start

[↑ Back to ansi ↑]

lines
ansi.erase.lines(count: number): string
out.ansi.erase.lines(count: number): string

Erase a specific number of lines upwards from the cursor

process.stdout.write(ansi.erase.lines(5)); // erases 5 lines upwards from the cursor
# Parameter Name Required Type Default Description
0 count No number 1 How many lines to erase
Return Type
string escape codes

[↑ Back to ansi ↑]

reserve
ansi.erase.reserve(count: number): string
out.ansi.erase.reserve(count: number): string

Make sure the next couple of lines are blank and on the screen

Note: Erases the current line and returns to it afterwards

process.stdout.write(ansi.erase.reserve(5)); // makes sure the next 5 lines are blank and on the screen
# Parameter Name Required Type Default Description
0 count No number 1 How many lines to reserve
Return Type
string escape codes

[↑ Back to ansi ↑]

clear

ansi.clear;
out.ansi.clear;

ANSI escape code to clear the terminal screen

process.stdout.write(ansi.clear); // clears the terminal screen

[↑ Back to ansi ↑]

beep

ansi.beep;
out.ansi.beep;

ANSI escape code to make the terminal beep

process.stdout.write(ansi.beep); // makes the terminal beep

[↑ Back to ansi ↑]

null

ansi.null;
out.ansi.null;

ANSI escape code for the NULL character. Can be used as a hidden marker.

process.stdout.write(ansi.null); // writes the NULL character

[↑ Back to ansi ↑]

getBreadcrumb

out.getBreadcrumb(...baseNames: string[]): Breadcrumb
getBreadcrumb(...baseNames: string[]): Breadcrumb

Provides a consistent format and style for questions/prompts

const bread = getBreadcrumb();
bread() // ''
bread('a') // 'a'
bread('a', 'b') // 'a › b'
bread('a', 'b', 'c') // 'a › b › c'

const sub = bread.sub('a', 'b');
sub(); // 'a › b'
sub('c') // 'a › b › c'
sub('c', 'd') // 'a › b › c › d'

const subsub = sub.sub('c', 'd');
subsub(); // 'a › b › c › d'
subsub('e'); // 'a › b › c › d › e'
# Parameter Name Required Type
0… baseNames No string[]
Return Type
Breadcrumb

[↑ Back to out ↑]

Breadcrumb

out.Breadcrumb;
Breadcrumb;

Return type for getBreadcrumb

[↑ Back to getBreadcrumb ↑]

getLineCounter

out.getLineCounter(): LineCounter
getLineCounter(): LineCounter

Get line counter for counter output lines

const lc = getLineCounter();
lc.log('hello'); // 1
lc.wrap(undefined, () => console.log('a single line')); // 1
lc.add(1);
lc.get(); // 3
lc.clear();
Return Type
LineCounter

[↑ Back to out ↑]

LineCounter

out.LineCounter;
LineCounter;

Return type for getLineCounter

const lc = getLineCounter();
lc.log('hello'); // 1
lc.wrap(1, () => console.log('a single line')); // 1
lc.add(1);
lc.get(); // 3
lc.clear();

[↑ Back to getLineCounter ↑]

lc.log

Same as console.log, but adds to the lc counter

const lc = getLineCounter();
lc.log('hello'); // 1
# Parameter Name Required Type Description
0… args Yes any[] The arguments to log
Return Type
number number of lines added

[↑ Back to getLineCounter ↑]

lc.overwrite

Similar to lc.log, but designed for overwriting lines that have already been printed on the screen

Use in combination with ansi.cursor.up to move the cursor up and replace/overwrite lines.

Adds a ansi.erase.lineEnd before each new line so that the line is cleared apart from what you're overwriting it with.

const lc = getLineCounter();
lc.overwrite('hello'); // 1
# Parameter Name Required Type Description
0… args Yes any[] The arguments to overwrite
Return Type
number number of lines added

[↑ Back to getLineCounter ↑]

lc.wrap

Wraps a function, and adds a given number to the line counter

const lc = getLineCounter();
lc.wrap(1, () => console.log('a single line')); // 1
# Parameter Name Required Type Description
0 newLines Yes number The number of lines to add
1 func Yes (...args: A[]) => number | T The function to wrap
2… args Yes A[] The arguments to pass to the function
Return Type
T result of the function

[↑ Back to getLineCounter ↑]

lc.add

Adds a given number to the line counter

const lc = getLineCounter();
lc.add(1);
# Parameter Name Required Type Description
0 newLines Yes number The number of lines to add
Return Type
void

[↑ Back to getLineCounter ↑]

lc.get

returns the line counter

const lc = getLineCounter();
lc.log('hello'); // 1
lc.wrap(1, () => console.log('a single line')); // 1
lc.add(1);
lc.get(); // 3
Return Type
number line counter

[↑ Back to getLineCounter ↑]

lc.getSince

Returns the number of lines since a given checkpoint

const lc = getLineCounter();
lc.log('hello'); // 1
lc.checkpoint('test-a');
lc.wrap(1, () => console.log('a single line')); // 1
lc.checkpoint('test-b');
lc.add(1);
lc.getSince('test-a'); // 2
lc.getSince('test-b'); // 1
# Parameter Name Required Type Description
0 checkpointID Yes string The checkpoint to check
Return Type
number number of lines since the checkpoint

[↑ Back to getLineCounter ↑]

lc.moveCursor

Move the cursor without clearing/erasing lines.

Updates the line count in the process.

# Parameter Name Required Type Description
0 y Yes number How many lines to move the cursor (down if positive, up if negative)
Return Type
void

[↑ Back to getLineCounter ↑]

lc.moveHome

Move the cursor to the start of the line count without clearing/erasing lines.

Same as lc.clear, but without clearing the lines.

Updates the line count in the process.

Return Type
void

[↑ Back to getLineCounter ↑]

lc.moveToCheckpoint

Move the cursor to a previously recorded checkpoint

Same as lc.clearToCheckpoint, but without clearing the lines.

Updates the line count in the process.

# Parameter Name Required Type Description
0 checkpointID Yes string The checkpoint to move to
Return Type
void

[↑ Back to getLineCounter ↑]

lc.clear

clears the line counter, and moves the cursor up by the value of the line counter

const lc = getLineCounter();
lc.log('hello'); // 1
lc.clear();
Return Type
void

[↑ Back to getLineCounter ↑]

lc.clearBack

Clears a given number of lines, and updates the line counter

const lc = getLineCounter();
lc.log('line 1'); // 1
lc.log('line 2'); // 1
lc.log('line 3'); // 1
lc.log('line 4'); // 1
lc.clearBack(2); // ('line 3' and 'line 4' are cleared)
# Parameter Name Required Type Description
0 linesToMoveBack Yes number The number of lines to clear
1 limitToRecordedLines No boolean Whether to limit the number of lines to clear to the number of lines recorded
Return Type
void

[↑ Back to getLineCounter ↑]

lc.clearDown

Moves the cursor down by a given number of lines

Can be negative to move up (clearing lines)

NOTE: This adds new lines

# Parameter Name Required Type Description
0 lines Yes number The number of lines to move
Return Type
void

[↑ Back to getLineCounter ↑]

lc.checkpoint

Records a 'checkpoint' that can be returned to later

const lc = getLineCounter();
lc.log('hello'); // 1
lc.checkpoint('test-a');
lc.wrap(1, () => console.log('a single line')); // 1
lc.checkpoint('test-b');
lc.add(1);
lc.getSince('test-a'); // 2
lc.getSince('test-b'); // 1
# Parameter Name Required Type Description
0 checkpointID No string The checkpoint to record
Return Type
string checkpointID

[↑ Back to getLineCounter ↑]

lc.clearToCheckpoint

Clear lines up to a previously recorded checkpoint

const lc = getLineCounter();
lc.log('line 1'); // 1
lc.log('line 2'); // 1
lc.checkpoint('test');
lc.log('line 3'); // 1
lc.log('line 4'); // 1
lc.clearToCheckpoint('test'); // ('line 3' and 'line 4' are cleared)
# Parameter Name Required Type Description
0 checkpointID Yes string The checkpoint to clear to
Return Type
void

[↑ Back to getLineCounter ↑]

lc.ansi

Get ansi codes for clear/erase functions, and update the line counter in the process.

[↑ Back to getLineCounter ↑]

lc.ansi.moveCursor

Move the cursor without clearing/erasing lines.

Updates the line count in the process.

WARNING: lc.ansi functions update the line count, but don't apply the affect themselves. You must print the returned string to apply the affect.

# Parameter Name Required Type Description
0 y Yes number How many lines to move the cursor (down if positive, up if negative)
Return Type
string

[↑ Back to getLineCounter ↑]

lc.ansi.moveHome

Move the cursor to the start of the line count without clearing/erasing lines.

Same as lc.clear, but without clearing the lines.

Updates the line count in the process.

WARNING: lc.ansi functions update the line count, but don't apply the affect themselves. You must print the returned string to apply the affect.

Return Type
string

[↑ Back to getLineCounter ↑]

lc.ansi.moveToCheckpoint

Move the cursor to a previously recorded checkpoint

Same as lc.clearToCheckpoint, but without clearing the lines.

Updates the line count in the process.

WARNING: lc.ansi functions update the line count, but don't apply the affect themselves. You must print the returned string to apply the affect.

# Parameter Name Required Type Description
0 checkpointID Yes string The checkpoint to move to
Return Type
string

[↑ Back to getLineCounter ↑]

lc.ansi.clear

Clears the line counter, and moves the cursor up by the value of the line counter

WARNING: lc.ansi functions update the line count, but don't apply the affect themselves. You must print the returned string to apply the affect.

const lc = getLineCounter();
lc.log('hello'); // 1
process.stdout.write(lc.ansi.clear());
Return Type
string

[↑ Back to getLineCounter ↑]

lc.ansi.clearBack

Clears a given number of lines, and updates the line counter

WARNING: lc.ansi functions update the line count, but don't apply the affect themselves. You must print the returned string to apply the affect.

const lc = getLineCounter();
lc.log('line 1'); // 1
lc.log('line 2'); // 1
lc.log('line 3'); // 1
lc.log('line 4'); // 1
process.stdout.write(lc.ansi.clearBack(2)); // ('line 3' and 'line 4' are cleared)
# Parameter Name Required Type Description
0 linesToMoveBack Yes number The number of lines to clear
1 limitToRecordedLines No boolean Whether to limit the number of lines to clear to the number of lines recorded
Return Type
string

[↑ Back to getLineCounter ↑]

lc.ansi.clearDown

Moves the cursor down by a given number of lines

Can be negative to move up (clearing lines)

NOTE: This adds new lines

WARNING: lc.ansi functions update the line count, but don't apply the affect themselves. You must print the returned string to apply the affect.

# Parameter Name Required Type Description
0 lines Yes number The number of lines to move
Return Type
string

[↑ Back to getLineCounter ↑]

lc.ansi.clearToCheckpoint

Clear lines up to a previously recorded checkpoint

WARNING: lc.ansi functions update the line count, but don't apply the affect themselves. You must print the returned string to apply the affect.

const lc = getLineCounter();
lc.log('line 1'); // 1
lc.log('line 2'); // 1
lc.checkpoint('test');
lc.log('line 3'); // 1
lc.log('line 4'); // 1
process.stdout.write(lc.ansi.clearToCheckpoint('test')); // ('line 3' and 'line 4' are cleared)
# Parameter Name Required Type Description
0 checkpointID Yes string The checkpoint to clear to
Return Type
string

[↑ Back to getLineCounter ↑]

lc.ansi.save

Saves the current cursor position and also tracks the line count

WARNING: lc.ansi functions update the line count, but don't apply the affect themselves. You must print the returned string to apply the affect.

[↑ Back to getLineCounter ↑]

lc.ansi.restore

Restores to the previously saved cursor position and also tracks the line count

WARNING: lc.ansi functions update the line count, but don't apply the affect themselves. You must print the returned string to apply the affect.

[↑ Back to getLineCounter ↑]

utils

getTerminalWidth

out.utils.getTerminalWidth(): number

Get maximum terminal width (columns)

print.utils.getTerminalWidth(); // 127
Return Type
number

[↑ Back to out ↑]

getLines

out.utils.getLines(text: Text): string[]

Split multi-line text into an array of lines

out.utils.getLines(`
this is line 1
this is line 2
`); // [ '', 'this is line 1', 'this is line 2', '' ]
# Parameter Name Required Type
0 text Yes Text
Return Type
string[]

[↑ Back to out ↑]

getNumLines

out.utils.getNumLines(text: Text): number

Get how many lines a string or array of lines has

out.utils.getNumLines(`
this is line 1
this is line 2
`); // 4
# Parameter Name Required Type
0 text Yes Text
Return Type
number

[↑ Back to out ↑]

getLinesWidth

out.utils.getLinesWidth(text: Text): number

Get how wide a string or array of lines has

out.utils.getLinesWidth(`
this is line 1
this is line 2
`) // 14
# Parameter Name Required Type
0 text Yes Text
Return Type
number

[↑ Back to out ↑]

getLogLines

out.utils.getLogLines(item: any): string[]

Split a log-formatted multi-line text into an array of lines

out.utils.getLogLines(`
this is line 1
this is line 2
`); // [ '', 'this is line 1', 'this is line 2', '' ]
# Parameter Name Required Type
0 item Yes any
Return Type
string[]

[↑ Back to out ↑]

getNumLogLines

out.utils.getNumLogLines(item: Text): number

Get how many lines a log-formatted string or array of lines has

out.utils.getNumLogLines(`
this is line 1
this is line 2
`); // 4
# Parameter Name Required Type
0 item Yes Text
Return Type
number

[↑ Back to out ↑]

getLogLinesWidth

out.utils.getLogLinesWidth(item: Text): number

Get how wide a log-formatted string or array of lines has

out.utils.getLogLinesWidth(`
this is line 1
this is line 2
`) // 14
# Parameter Name Required Type
0 item Yes Text
Return Type
number

[↑ Back to out ↑]

joinLines

out.utils.joinLines(lines: string[]): string

Join an array of lines into a single multi-line string

out.utils.joinLines(['this is line 1', 'this is line 2'])
// 'this is line 1' + '\n' +
// 'this is line 2'
# Parameter Name Required Type
0 lines Yes string[]
Return Type
string

[↑ Back to out ↑]

hasColor

out.utils.hasColor(str: string): boolean

Determine whether a given string contains any colr-ed colours

out.utils.hasColor('this is line 1') // false
out.utils.hasColor(colr.red('this is line 1')) // true
# Parameter Name Required Type
0 str Yes string
Return Type
boolean

[↑ Back to out ↑]

stripAnsi

out.utils.stripAnsi(text: string): string

Removes all ANSI escape codes from a string. This includes any colour or styling added by colr or libraries like chalk.

# Parameter Name Required Type
0 text Yes string
Return Type
string

[↑ Back to out ↑]

getEmojiRegex

out.utils.getEmojiRegex(flags: string): RegExp

A rough way to regex emojis

Note: Certain symbols removed to minimise false positives

# Parameter Name Required Type Default
0 flags No string 'g'
Return Type
RegExp

[↑ Back to out ↑]

colr

colr;

Tool for creating coloured/styled strings

Chain/combine different combinations of colours and styles to get the appearance you want.

Name Type Modifier Description
light Text Light colr.light() Use light text colours (on by default)
dark Text Dark colr.dark() Use dark text colours
lightBg Background Light colr.lightBg() Use light background colours (on by default)
darkBg Background Dark colr.darkBg() Use dark background colours
Name Affects Colour Type Recommended Alt
red Text 🟥 Red Base (Light) colr.red()
darkRed Text 🟥 Red Dark colr.dark.red() colr.darkRed()
lightRed Text 🟥 Red Light colr.light.red() colr.lightRed()
green Text 🟩 Green Base (Light) colr.green()
darkGreen Text 🟩 Green Dark colr.dark.green() colr.darkGreen()
lightGreen Text 🟩 Green Light colr.light.green() colr.lightGreen()
yellow Text 🟨 Yellow Base (Light) colr.yellow()
darkYellow Text 🟨 Yellow Dark colr.dark.yellow() colr.darkYellow()
lightYellow Text 🟨 Yellow Light colr.light.yellow() colr.lightYellow()
blue Text 🟦 Blue Base (Light) colr.blue()
darkBlue Text 🟦 Blue Dark colr.dark.blue() colr.darkBlue()
lightBlue Text 🟦 Blue Light colr.light.blue() colr.lightBlue()
magenta Text 🟪 Magenta Base (Light) colr.magenta()
darkMagenta Text 🟪 Magenta Dark colr.dark.magenta() colr.darkMagenta()
lightMagenta Text 🟪 Magenta Light colr.light.magenta() colr.lightMagenta()
cyan Text 💠 Cyan Base (Light) colr.cyan()
darkCyan Text 💠 Cyan Dark colr.dark.cyan() colr.darkCyan()
lightCyan Text 💠 Cyan Light colr.light.cyan() colr.lightCyan()
white Text ⬜ White Base (Light) colr.white()
darkWhite Text ⬜ White Dark colr.dark.white() colr.darkWhite()
lightWhite Text ⬜ White Light colr.light.white() colr.lightWhite()
redBg Background 🟥 Red Base (Light) colr.redBg()
darkRedBg Background 🟥 Red Dark colr.darkBg.redBg() colr.darkRedBg()
lightRedBg Background 🟥 Red Light colr.lightBg.redBg() colr.lightRedBg()
greenBg Background 🟩 Green Base (Light) colr.greenBg()
darkGreenBg Background 🟩 Green Dark colr.darkBg.greenBg() colr.darkGreenBg()
lightGreenBg Background 🟩 Green Light colr.lightBg.greenBg() colr.lightGreenBg()
yellowBg Background 🟨 Yellow Base (Light) colr.yellowBg()
darkYellowBg Background 🟨 Yellow Dark colr.darkBg.yellowBg() colr.darkYellowBg()
lightYellowBg Background 🟨 Yellow Light colr.lightBg.yellowBg() colr.lightYellowBg()
blueBg Background 🟦 Blue Base (Light) colr.blueBg()
darkBlueBg Background 🟦 Blue Dark colr.darkBg.blueBg() colr.darkBlueBg()
lightBlueBg Background 🟦 Blue Light colr.lightBg.blueBg() colr.lightBlueBg()
magentaBg Background 🟪 Magenta Base (Light) colr.magentaBg()
darkMagentaBg Background 🟪 Magenta Dark colr.darkBg.magentaBg() colr.darkMagentaBg()
lightMagentaBg Background 🟪 Magenta Light colr.lightBg.magentaBg() colr.lightMagentaBg()
cyanBg Background 💠 Cyan Base (Light) colr.cyanBg()
darkCyanBg Background 💠 Cyan Dark colr.darkBg.cyanBg() colr.darkCyanBg()
lightCyanBg Background 💠 Cyan Light colr.lightBg.cyanBg() colr.lightCyanBg()
whiteBg Background ⬜ White Base (Light) colr.whiteBg()
darkWhiteBg Background ⬜ White Dark colr.darkBg.whiteBg() colr.darkWhiteBg()
lightWhiteBg Background ⬜ White Light colr.lightBg.whiteBg() colr.lightWhiteBg()
black Text ⬛ Black Always Dark colr.black()
darkBlack Text ⬛ Black Dark colr.black() colr.darkBlack()
lightBlack Text ⬛ Black Light colr.light.black() colr.lightBlack()
blackBg Background ⬛ Black Always Dark colr.blackBg()
darkBlackBg Background ⬛ Black Dark colr.blackBg() colr.darkBlackBg()
lightBlackBg Background ⬛ Black Light colr.lightBg.blackBg() colr.lightBlackBg()
grey Text 🩶 Grey Greys colr.grey()
greyBg Background 🩶 Grey Greys colr.greyBg()
grey0 Text ⬛ Black Greys colr.grey0()
grey1 Text 🩶 Grey Greys colr.grey1()
grey2 Text 🩶 Grey Greys colr.grey2()
grey3 Text 🩶 Grey Greys colr.grey3()
grey4 Text 🩶 Grey Greys colr.grey4()
grey5 Text ⬜ White Greys colr.grey5()
primary Text 🟨 Yellow Theme colr.primary()
secondary Text 🟪 Magenta Theme colr.secondary()
success Text 🟩 Green Theme colr.success()
danger Text 🟥 Red Theme colr.danger()
warning Text 🟨 Yellow Theme colr.warning()
info Text 🟦 Blue Theme colr.info()
primaryBg Background 🟨 Yellow Theme colr.primaryBg()
secondaryBg Background 🟪 Magenta Theme colr.secondaryBg()
successBg Background 🟩 Green Theme colr.successBg()
dangerBg Background 🟥 Red Theme colr.dangerBg()
warningBg Background 🟨 Yellow Theme colr.warningBg()
infoBg Background 🟦 Blue Theme colr.infoBg()
Name Description
reset colr.reset('') This returns the text back to normal colours/styles
bold colr.bold('') This makes the text bold
dim colr.dim('') This dims the brightness of the text colour
italic colr.italic('') This makes the text italic
overline colr.overline('') This adds a horizontal line above the text
underline colr.underline('') This adds a horizontal line below the text
strikethrough colr.strikethrough('') This add a horizontal line through the middle of the given text
inverse colr.inverse('') This inverses the text and background colours for the given text
hidden colr.hidden('') This makes the text invisible.
colr.yellow('Hello World!'); // 'Hello World!' with yellow text
colr.dark.yellow('Hello World!'); // 'Hello World!' with dark yellow text
colr.yellow.dim('Hello World!'); // 'Hello World!' with dimmed yellow text
colr.dark.yellow.dim('Hello World!'); // 'Hello World!' with dimmed dark yellow text

colr.yellow.blueBg('Hello World!'); // 'Hello World!' with yellow text and blue background
colr.yellow.darkBg.blueBg('Hello World!'); // 'Hello World!' with yellow text and dark blue background

// pass in multiple arguments to get them all coloured/styled
colr.red('Hello', 'World!'); // 'Hello World!' with red text

// nested styles
colr.red(`A ${colr.blue('blue')} world`); // 'A blue world' with with red text, except 'blue' which is blue

// template literals
colr.red.$`A ${'red'} world`; // 'A red world' with default colours, except 'World!' which is red

// Debugging
colr.debug(colr.yellow.blueBg(`A ${colr.red('red')} world`)); // '(YLW>){blu>}A (RED>)red(<)(YLW>) world{<}(<)'

[↑ Back to top ↑]

Option Modifiers

light

colr.light(...text: string[]): string

Modifies base (red, blue, green, etc) text colours to use the light version of the colour.

light is on by default.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.light.red('Hello World!'); // 'Hello World!' with light red text
colr.red.light('Hello World!'); // 'Hello World!' with light red text
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

dark

colr.dark(...text: string[]): string

Modifies base (red, blue, green, etc) text colours to use the dark version of the colour.

dark is off by default (defaults to light).

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.dark.red('Hello World!'); // 'Hello World!' with dark red text
colr.red.dark('Hello World!'); // 'Hello World!' with dark red text
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightBg

colr.lightBg(...text: string[]): string

Modifies base (redBg, blueBg, greenBg, etc) background colours to use the light version of the colour.

lightBg is on by default.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.lightBg.redBg('Hello World!'); // 'Hello World!' with a light red background
colr.redBg.lightBg('Hello World!'); // 'Hello World!' with a light red background
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkBg

colr.darkBg(...text: string[]): string

Modifies base (redBg, blueBg, greenBg, etc) background colours to use the dark version of the colour.

darkBg is off by default (defaults to lightBg).

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.darkBg.redBg('Hello World!'); // 'Hello World!' with a dark red background
colr.redBg.darkBg('Hello World!'); // 'Hello World!' with a dark red background
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

Text Colours

red

colr.red(...text: string[]): string

Makes the given text red.

Uses lightRed by default, or if light modifier is used in the chain. Uses darkRed if dark modifier is used in the chain.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.red('Hello World!'); // 'Hello World!' with __light__ red text
colr.light.red('Hello World!'); // 'Hello World!' with __light__ red text
colr.dark.red('Hello World!'); // 'Hello World!' with __dark__ red text
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkRed
colr.darkRed(...text: string[]): string
colr.dark.red(...text: string[]): string

Makes the given text dark red.

Unaffected by light/dark modifiers and will always be dark.

Prefer dark.red

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightRed
colr.lightRed(...text: string[]): string
colr.light.red(...text: string[]): string
colr.red(...text: string[]): string

Makes the given text light red.

Unaffected by light/dark modifiers and will always be light.

Prefer light.red

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

green

colr.green(...text: string[]): string

Makes the given text green.

Uses lightGreen by default, or if light modifier is used in the chain. Uses darkGreen if dark modifier is used in the chain.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.green('Hello World!'); // 'Hello World!' with __light__ green text
colr.light.green('Hello World!'); // 'Hello World!' with __light__ green text
colr.dark.green('Hello World!'); // 'Hello World!' with __dark__ green text
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkGreen
colr.darkGreen(...text: string[]): string
colr.dark.green(...text: string[]): string

Makes the given text dark green.

Unaffected by light/dark modifiers and will always be dark.

Prefer dark.green

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightGreen
colr.lightGreen(...text: string[]): string
colr.light.green(...text: string[]): string
colr.green(...text: string[]): string

Makes the given text light green.

Unaffected by light/dark modifiers and will always be light.

Prefer light.green

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

yellow

colr.yellow(...text: string[]): string

Makes the given text yellow.

Uses lightYellow by default, or if light modifier is used in the chain. Uses darkYellow if dark modifier is used in the chain.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.yellow('Hello World!'); // 'Hello World!' with __light__ yellow text
colr.light.yellow('Hello World!'); // 'Hello World!' with __light__ yellow text
colr.dark.yellow('Hello World!'); // 'Hello World!' with __dark__ yellow text
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkYellow
colr.darkYellow(...text: string[]): string
colr.dark.yellow(...text: string[]): string

Makes the given text dark yellow.

Unaffected by light/dark modifiers and will always be dark.

Prefer dark.yellow

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightYellow
colr.lightYellow(...text: string[]): string
colr.light.yellow(...text: string[]): string
colr.yellow(...text: string[]): string

Makes the given text light yellow.

Unaffected by light/dark modifiers and will always be light.

Prefer light.yellow

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

blue

colr.blue(...text: string[]): string

Makes the given text blue.

Uses lightBlue by default, or if light modifier is used in the chain. Uses darkBlue if dark modifier is used in the chain.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.blue('Hello World!'); // 'Hello World!' with __light__ blue text
colr.light.blue('Hello World!'); // 'Hello World!' with __light__ blue text
colr.dark.blue('Hello World!'); // 'Hello World!' with __dark__ blue text
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkBlue
colr.darkBlue(...text: string[]): string
colr.dark.blue(...text: string[]): string

Makes the given text dark blue.

Unaffected by light/dark modifiers and will always be dark.

Prefer dark.blue

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightBlue
colr.lightBlue(...text: string[]): string
colr.light.blue(...text: string[]): string
colr.blue(...text: string[]): string

Makes the given text light blue.

Unaffected by light/dark modifiers and will always be light.

Prefer light.blue

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

magenta

colr.magenta(...text: string[]): string

Makes the given text magenta.

Uses lightMagenta by default, or if light modifier is used in the chain. Uses darkMagenta if dark modifier is used in the chain.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.magenta('Hello World!'); // 'Hello World!' with __light__ magenta text
colr.light.magenta('Hello World!'); // 'Hello World!' with __light__ magenta text
colr.dark.magenta('Hello World!'); // 'Hello World!' with __dark__ magenta text
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkMagenta
colr.darkMagenta(...text: string[]): string
colr.dark.magenta(...text: string[]): string

Makes the given text dark magenta.

Unaffected by light/dark modifiers and will always be dark.

Prefer dark.magenta

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightMagenta
colr.lightMagenta(...text: string[]): string
colr.light.magenta(...text: string[]): string
colr.magenta(...text: string[]): string

Makes the given text light magenta.

Unaffected by light/dark modifiers and will always be light.

Prefer light.magenta

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

cyan

colr.cyan(...text: string[]): string

Makes the given text cyan.

Uses lightCyan by default, or if light modifier is used in the chain. Uses darkCyan if dark modifier is used in the chain.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.cyan('Hello World!'); // 'Hello World!' with __light__ cyan text
colr.light.cyan('Hello World!'); // 'Hello World!' with __light__ cyan text
colr.dark.cyan('Hello World!'); // 'Hello World!' with __dark__ cyan text
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkCyan
colr.darkCyan(...text: string[]): string
colr.dark.cyan(...text: string[]): string

Makes the given text dark cyan.

Unaffected by light/dark modifiers and will always be dark.

Prefer dark.cyan

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightCyan
colr.lightCyan(...text: string[]): string
colr.light.cyan(...text: string[]): string
colr.cyan(...text: string[]): string

Makes the given text light cyan.

Unaffected by light/dark modifiers and will always be light.

Prefer light.cyan

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

white

colr.white(...text: string[]): string

Makes the given text white.

Uses lightWhite by default, or if light modifier is used in the chain. Uses darkWhite if dark modifier is used in the chain.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.white('Hello World!'); // 'Hello World!' with __light__ white text
colr.light.white('Hello World!'); // 'Hello World!' with __light__ white text
colr.dark.white('Hello World!'); // 'Hello World!' with __dark__ white text
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkWhite
colr.darkWhite(...text: string[]): string
colr.dark.white(...text: string[]): string

Makes the given text dark white.

Unaffected by light/dark modifiers and will always be dark.

Prefer dark.white

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightWhite
colr.lightWhite(...text: string[]): string
colr.light.white(...text: string[]): string
colr.white(...text: string[]): string

Makes the given text light white.

Unaffected by light/dark modifiers and will always be light.

Prefer light.white

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

Background Colours

redBg

colr.redBg(...text: string[]): string

Makes the background of the given text red.

Uses lightRedBg by default, or if lightBg modifier is used in the chain. Uses darkRedBg if darkBg modifier is used in the chain.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.redBg('Hello World!'); // 'Hello World!' with a __light__ red background
colr.lightBg.redBg('Hello World!'); // 'Hello World!' with a __light__ red background
colr.darkBg.redBg('Hello World!'); // 'Hello World!' with a __dark__ red background
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkRedBg
colr.darkRedBg(...text: string[]): string
colr.darkBg.redBg(...text: string[]): string
colr.redBg(...text: string[]): string

Makes the background of the given text dark red.

Unaffected by lightBg/darkBg modifiers and will always be dark.

Prefer darkBg.redBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightRedBg
colr.lightBg.redBg(...text: string[]): string
colr.lightRedBg(...text: string[]): string

Makes the background of the given text light red.

Unaffected by lightBg/darkBg modifiers and will always be light.

Prefer lightBg.redBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

greenBg

colr.greenBg(...text: string[]): string

Makes the background of the given text green.

Uses lightGreenBg by default, or if lightBg modifier is used in the chain. Uses darkGreenBg if darkBg modifier is used in the chain.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.greenBg('Hello World!'); // 'Hello World!' with a __light__ green background
colr.lightBg.greenBg('Hello World!'); // 'Hello World!' with a __light__ green background
colr.darkBg.greenBg('Hello World!'); // 'Hello World!' with a __dark__ green background
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkGreenBg
colr.darkGreenBg(...text: string[]): string
colr.darkBg.greenBg(...text: string[]): string
colr.greenBg(...text: string[]): string

Makes the background of the given text dark green.

Unaffected by lightBg/darkBg modifiers and will always be dark.

Prefer darkBg.greenBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightGreenBg
colr.lightBg.greenBg(...text: string[]): string
colr.lightGreenBg(...text: string[]): string

Makes the background of the given text light green.

Unaffected by lightBg/darkBg modifiers and will always be light.

Prefer lightBg.greenBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

yellowBg

colr.yellowBg(...text: string[]): string

Makes the background of the given text yellow.

Uses lightYellowBg by default, or if lightBg modifier is used in the chain. Uses darkYellowBg if darkBg modifier is used in the chain.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.yellowBg('Hello World!'); // 'Hello World!' with a __light__ yellow background
colr.lightBg.yellowBg('Hello World!'); // 'Hello World!' with a __light__ yellow background
colr.darkBg.yellowBg('Hello World!'); // 'Hello World!' with a __dark__ yellow background
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkYellowBg
colr.darkYellowBg(...text: string[]): string
colr.darkBg.yellowBg(...text: string[]): string
colr.yellowBg(...text: string[]): string

Makes the background of the given text dark yellow.

Unaffected by lightBg/darkBg modifiers and will always be dark.

Prefer darkBg.yellowBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightYellowBg
colr.lightBg.yellowBg(...text: string[]): string
colr.lightYellowBg(...text: string[]): string

Makes the background of the given text light yellow.

Unaffected by lightBg/darkBg modifiers and will always be light.

Prefer lightBg.yellowBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

blueBg

colr.blueBg(...text: string[]): string

Makes the background of the given text blue.

Uses lightBlueBg by default, or if lightBg modifier is used in the chain. Uses darkBlueBg if darkBg modifier is used in the chain.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.blueBg('Hello World!'); // 'Hello World!' with a __light__ blue background
colr.lightBg.blueBg('Hello World!'); // 'Hello World!' with a __light__ blue background
colr.darkBg.blueBg('Hello World!'); // 'Hello World!' with a __dark__ blue background
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkBlueBg
colr.darkBlueBg(...text: string[]): string
colr.darkBg.blueBg(...text: string[]): string
colr.blueBg(...text: string[]): string

Makes the background of the given text dark blue.

Unaffected by lightBg/darkBg modifiers and will always be dark.

Prefer darkBg.blueBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightBlueBg
colr.lightBg.blueBg(...text: string[]): string
colr.lightBlueBg(...text: string[]): string

Makes the background of the given text light blue.

Unaffected by lightBg/darkBg modifiers and will always be light.

Prefer lightBg.blueBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

magentaBg

colr.magentaBg(...text: string[]): string

Makes the background of the given text magenta.

Uses lightMagentaBg by default, or if lightBg modifier is used in the chain. Uses darkMagentaBg if darkBg modifier is used in the chain.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.magentaBg('Hello World!'); // 'Hello World!' with a __light__ magenta background
colr.lightBg.magentaBg('Hello World!'); // 'Hello World!' with a __light__ magenta background
colr.darkBg.magentaBg('Hello World!'); // 'Hello World!' with a __dark__ magenta background
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkMagentaBg
colr.darkMagentaBg(...text: string[]): string
colr.darkBg.magentaBg(...text: string[]): string
colr.magentaBg(...text: string[]): string

Makes the background of the given text dark magenta.

Unaffected by lightBg/darkBg modifiers and will always be dark.

Prefer darkBg.magentaBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightMagentaBg
colr.lightBg.magentaBg(...text: string[]): string
colr.lightMagentaBg(...text: string[]): string

Makes the background of the given text light magenta.

Unaffected by lightBg/darkBg modifiers and will always be light.

Prefer lightBg.magentaBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

cyanBg

colr.cyanBg(...text: string[]): string

Makes the background of the given text cyan.

Uses lightCyanBg by default, or if lightBg modifier is used in the chain. Uses darkCyanBg if darkBg modifier is used in the chain.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.cyanBg('Hello World!'); // 'Hello World!' with a __light__ cyan background
colr.lightBg.cyanBg('Hello World!'); // 'Hello World!' with a __light__ cyan background
colr.darkBg.cyanBg('Hello World!'); // 'Hello World!' with a __dark__ cyan background
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkCyanBg
colr.darkCyanBg(...text: string[]): string
colr.darkBg.cyanBg(...text: string[]): string
colr.cyanBg(...text: string[]): string

Makes the background of the given text dark cyan.

Unaffected by lightBg/darkBg modifiers and will always be dark.

Prefer darkBg.cyanBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightCyanBg
colr.lightBg.cyanBg(...text: string[]): string
colr.lightCyanBg(...text: string[]): string

Makes the background of the given text light cyan.

Unaffected by lightBg/darkBg modifiers and will always be light.

Prefer lightBg.cyanBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

whiteBg

colr.whiteBg(...text: string[]): string

Makes the background of the given text white.

Uses lightWhiteBg by default, or if lightBg modifier is used in the chain. Uses darkWhiteBg if darkBg modifier is used in the chain.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.whiteBg('Hello World!'); // 'Hello World!' with a __light__ white background
colr.lightBg.whiteBg('Hello World!'); // 'Hello World!' with a __light__ white background
colr.darkBg.whiteBg('Hello World!'); // 'Hello World!' with a __dark__ white background
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkWhiteBg
colr.darkWhiteBg(...text: string[]): string
colr.darkBg.whiteBg(...text: string[]): string
colr.whiteBg(...text: string[]): string

Makes the background of the given text dark white.

Unaffected by lightBg/darkBg modifiers and will always be dark.

Prefer darkBg.whiteBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightWhiteBg
colr.lightBg.whiteBg(...text: string[]): string
colr.lightWhiteBg(...text: string[]): string

Makes the background of the given text light white.

Unaffected by lightBg/darkBg modifiers and will always be light.

Prefer lightBg.whiteBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

Black Colours

black

colr.black(...text: string[]): string
colr.darkBlack(...text: string[]): string

Note: Black behaves differently to other colours as the 'base' is always dark, regardless of modifiers.

Makes the given text dark black.

Unaffected by light/dark modifiers and will always be dark.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.black('Hello World!'); // 'Hello World!' with __dark__ black text
colr.light.black('Hello World!'); // 'Hello World!' with __dark__ black text
colr.dark.black('Hello World!'); // 'Hello World!' with __dark__ black text
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkBlack
colr.black(...text: string[]): string
colr.darkBlack(...text: string[]): string

Makes the given text dark black.

Unaffected by light/dark modifiers and will always be dark.

Same as black.

Note: Black behaves differently to other colours as the 'base' is always dark, regardless of modifiers.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightBlack
colr.lightBlack(...text: string[]): string

Makes the given text light black.

Unaffected by light/dark modifiers and will always be light.

Note: Black behaves differently to other colours as the 'base' is always dark, regardless of modifiers.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

blackBg

colr.blackBg(...text: string[]): string
colr.darkBlackBg(...text: string[]): string

Note: Black behaves differently to other colours as the 'base' is always dark, regardless of modifiers.

Makes the background of the given text dark black.

Unaffected by lightBg/darkBg modifiers and will always be dark.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

colr.blackBg('Hello World!'); // 'Hello World!' with a __dark__ black background
colr.lightBg.blackBg('Hello World!'); // 'Hello World!' with a __dark__ black background
colr.darkBg.blackBg('Hello World!'); // 'Hello World!' with a __dark__ black background
# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

darkBlackBg
colr.blackBg(...text: string[]): string
colr.darkBlackBg(...text: string[]): string

Makes the background of the given text dark black.

Unaffected by lightBg/darkBg modifiers and will always be dark.

Same as blackBg.

Note: Black behaves differently to other colours as the 'base' is always dark, regardless of modifiers.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

lightBlackBg
colr.lightBlackBg(...text: string[]): string

Makes the background of the given text light black.

Unaffected by lightBg/darkBg modifiers and will always be light.

Note: Black behaves differently to other colours as the 'base' is always dark, regardless of modifiers.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

Grey / Gray Colours

grey / gray

colr.grey(...text: string[]): string
colr.gray(...text: string[]): string

Makes the given text grey.

Equivalent to colr.light.black.

Unaffected by light/dark modifiers

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

greyBg / grayBg

colr.greyBg(...text: string[]): string
colr.grayBg(...text: string[]): string

Makes the background of the given text grey.

Equivalent to colr.lightBg.blackBg.

Unaffected by lightBg/darkBg modifiers

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

grey0 / gray0

colr.grey0(...text: string[]): string
colr.gray0(...text: string[]): string

Makes the given text grey. 0 out of 5 (where 0 is black and 5 is white).

Equivalent to colr.black.

Unaffected by light/dark modifiers

Warning: Numbered greys may not inverse as expected. colr.grey0.inversecolr.blackBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

grey1 / gray1

colr.grey1(...text: string[]): string
colr.gray1(...text: string[]): string

Makes the given text grey. 1 out of 5 (where 0 is black and 5 is white).

Equivalent to colr.light.black.dim.

Unaffected by light/dark modifiers

Warning: Numbered greys may not inverse as expected. colr.grey1.inversecolr.lightBlackBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

grey2 / gray2

colr.grey2(...text: string[]): string
colr.gray2(...text: string[]): string

Makes the given text grey. 2 out of 5 (where 0 is black and 5 is white).

Equivalent to colr.dark.white.dim.

Unaffected by light/dark modifiers

Warning: Numbered greys may not inverse as expected. colr.grey2.inversecolr.darkWhiteBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

grey3 / gray3

colr.grey3(...text: string[]): string
colr.gray3(...text: string[]): string

Makes the given text grey. 3 out of 5 (where 0 is black and 5 is white).

Equivalent to colr.light.white.dim.

Unaffected by light/dark modifiers

Warning: Numbered greys may not inverse as expected. colr.grey3.inversecolr.whiteBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

grey4 / gray4

colr.grey4(...text: string[]): string
colr.gray4(...text: string[]): string

Makes the given text grey. 4 out of 5 (where 0 is black and 5 is white).

Equivalent to colr.dark.white.

Unaffected by light/dark modifiers

Warning: Numbered greys may not inverse as expected. colr.grey4.inversecolr.darkWhiteBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

grey5 / gray5

colr.grey5(...text: string[]): string
colr.gray5(...text: string[]): string

Makes the given text grey. 5 out of 5 (where 0 is black and 5 is white).

Equivalent to colr.light.white.

Unaffected by light/dark modifiers

Warning: Numbered greys may not inverse as expected. colr.grey5.inversecolr.whiteBg

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

Theme Colours

primary

colr.primary(...text: string[]): string

Makes the given text 'primary' (light yellow) themed.

Equivalent to colr.light.yellow.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

secondary

colr.secondary(...text: string[]): string

Makes the given text 'secondary' (magenta) themed.

Equivalent to colr.light.magenta.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

success

colr.success(...text: string[]): string

Makes the given text 'success' (green) themed.

Equivalent to colr.light.green.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

danger

colr.danger(...text: string[]): string

Makes the given text 'danger' (red) themed.

Equivalent to colr.dark.red.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

warning

colr.warning(...text: string[]): string

Makes the given text 'warning' (dark yellow) themed.

Equivalent to colr.dark.yellow.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

info

colr.info(...text: string[]): string

Makes the given text 'info' (blue) themed.

Equivalent to colr.light.blue.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

primaryBg

colr.primaryBg(...text: string[]): string

Makes the background of the given text 'primary' (light yellow) themed and makes the text black.

Equivalent to colr.lightBg.yellowBg.black.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

secondaryBg

colr.secondaryBg(...text: string[]): string

Makes the background of the given text 'secondary' (magenta) themed and makes the text black.

Equivalent to colr.lightBg.magentaBg.black.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

successBg

colr.successBg(...text: string[]): string

Makes the background of the given text 'success' (green) themed and makes the text black.

Equivalent to colr.lightBg.greenBg.black.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

dangerBg

colr.dangerBg(...text: string[]): string

Makes the background of the given text 'danger' (red) themed and makes the text black.

Equivalent to colr.darkBg.redBg.black.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

warningBg

colr.warningBg(...text: string[]): string

Makes the background of the given text 'warning' (dark yellow) themed and makes the text black.

Equivalent to colr.darkBg.yellowBg.black.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

infoBg

colr.infoBg(...text: string[]): string

Makes the background of the given text 'info' (blue) themed and makes the text black.

Equivalent to colr.lightBg.blueBg.black.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

Other Styles

reset

colr.reset(...text: string[]): string

Applies the 'reset' style to the given text.

This returns the text back to normal colours/styles.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

bold

colr.bold(...text: string[]): string

Applies the 'bold' style to the given text.

This makes the text bold.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

dim

colr.dim(...text: string[]): string

Applies the 'dim' style to the given text.

This dims the brightness of the text colour.

Note: Not the same as dark colours.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

italic

colr.italic(...text: string[]): string

Applies the 'italic' style to the given text.

This makes the text italic.

Note: Not widely supported

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

overline

colr.overline(...text: string[]): string

Applies the 'overline' style to the given text.

This adds a horizontal line above the text

Note: Not widely supported

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

underline

colr.underline(...text: string[]): string

Applies the 'underline' style to the given text.

This adds a horizontal line below the text

Note: Not widely supported

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

strikethrough

colr.strikethrough(...text: string[]): string

Applies the 'strikethrough' style to the given text.

This add a horizontal line through the middle of the given text.

Note: Not widely supported

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

inverse

colr.inverse(...text: string[]): string

Applies the 'inverse' style to the given text.

This inverses the text and background colours for the given text.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

hidden

colr.hidden(...text: string[]): string

Applies the 'hidden' style to the given text.

This makes the text invisible.

Note: A ColrFn - so can be used as a function, or chained with more colours/styles

# Parameter Name Required Type
0… text Yes string[]
Return Type
string

[↑ Back to colr ↑]

Helper Functions

$ / template

colr.$;
colr.template;

A helper function to make it easier to use colr with template strings.

Applies the given template string to the $'d expressions in the template string.

colr.red.$`A ${'red'} world`; // 'A red world' with default colours, except 'World!' which is red
colr.red.template`A ${'red'} world`; // 'A red world' with default colours, except 'World!' which is red

colr.blueBg(colr.red.$`A ${'red'} word in a blue world`); // 'A red word in a blue world' with a blue background, and 'red' has red text

[↑ Back to colr ↑]

clear

colr.clear;

Removes all colr ANSI escapes code from the given text.

const text = colr.red('Hello World!'); // 'Hello World!' with red text
colr.clear(text); // 'Hello World!' with no colours

[↑ Back to colr ↑]

debug

colr.debug;

Replaces all colr ANSI escapes code with human readable indicators to help debugging why a style might not be working.

  • Each colour/style has a 3 letter key and is wrapped in backets with a direction indicator.
  • The direction indicator is > for opening and < for closing.
  • The key is uppercase for light colours, and lowercase for dark colours.
  • The key is wrapped in () for text colours, {} for background colours, and [] for other styles.
  • Colours have common ending codes, so (<) (text) or {<} (background) is used for these codes.
Colour Light Text Dark Text Light BG Dark BG
black (BLK>)...(<) (blk>)...(<) {BLK>}...{<} {blk>}...{<}
red (RED>)...(<) (red>)...(<) {RED>}...{<} {red>}...{<}
green (GRN>)...(<) (grn>)...(<) {GRN>}...{<} {grn>}...{<}
yellow (YLW>)...(<) (ylw>)...(<) {YLW>}...{<} {ylw>}...{<}
blue (BLU>)...(<) (blu>)...(<) {BLU>}...{<} {blu>}...{<}
magenta (MAG>)...(<) (mag>)...(<) {MAG>}...{<} {mag>}...{<}
cyan (CYN>)...(<) (cyn>)...(<) {CYN>}...{<} {cyn>}...{<}
white (WHT>)...(<) (wht>)...(<) {WHT>}...{<} {wht>}...{<}
Style
reset [rst>]...[<rst]
bold [bld>]...[<bld]
dim [dim>]...[<dim]
italic [itl>]...[<itl]
overline [ovr>]...[<ovr]
underline [und>]...[<und]
strikethrough [str>]...[<str]
inverse [inv>]...[<inv]
hidden [hdn>]...[<hdn]
colr.debug(colr.yellow('Hello World!')); // '(YLW>)Hello World!(<)'
colr.debug(colr.dark.yellow('Hello World!')); // '(ylw>)Hello World!(<)'
colr.debug(colr.yellow.dim('Hello World!')); // '(YLW>)[dim>]Hello World![<dim](<)'
colr.debug(colr.dark.yellow.dim('Hello World!')); // '(ylw>)[dim>]Hello World![<dim](<)'

colr.debug(colr.yellow.blueBg('Hello World!')); // '(YLW>){blu>}Hello World!{<}(<)'
colr.debug(colr.yellow.lightBg.blueBg('Hello World!')); // '(YLW>){BLU>}Hello World!{<}(<)'

[↑ Back to colr ↑]

sets

colr.sets;

A collection of different colour 'sets'.

A set is a collection of ColrFn's for a certain colour/theme that affect the text or the background.

Useful for when you want to attribute a certain colour/theme, and apply it to the text colour or background colour in different applications.

Name text bg
red colr.red colr.redBg
green colr.green colr.greenBg
yellow colr.yellow colr.yellowBg
blue colr.blue colr.blueBg
magenta colr.magenta colr.magentaBg
cyan colr.cyan colr.cyanBg
white colr.white colr.whiteBg
black colr.black colr.blackBg
lightBlack colr.lightBlack colr.lightBlackBg
grey colr.grey colr.greyBg
gray colr.gray colr.grayBg
primary colr.primary colr.primaryBg
secondary colr.secondary colr.secondaryBg
success colr.success colr.successBg
danger colr.danger colr.dangerBg
warning colr.warning colr.warningBg
info colr.info colr.infoBg
const printOption = (name: string, colour: ColrSet) => {
  console.log(' ' + colour.bg.darkBlack('   ') + ' ' + colour.text(name));
};
printOption('Approve', colr.lightBg.sets.green);
printOption('Decline', colr.dark.sets.red);

// Rough output:
// '███ Approve' in green
// '███ Decline' in red

[↑ Back to colr ↑]

red

colr.sets.red;

A ColrSet object for the colour red.

  • The text function is: colr.red.
  • The bg function is: colr.redBg.

[↑ Back to colr ↑]

green

colr.sets.green;

A ColrSet object for the colour green.

  • The text function is: colr.green.
  • The bg function is: colr.greenBg.

[↑ Back to colr ↑]

yellow

colr.sets.yellow;

A ColrSet object for the colour yellow.

  • The text function is: colr.yellow.
  • The bg function is: colr.yellowBg.

[↑ Back to colr ↑]

blue

colr.sets.blue;

A ColrSet object for the colour blue.

  • The text function is: colr.blue.
  • The bg function is: colr.blueBg.

[↑ Back to colr ↑]

magenta

colr.sets.magenta;

A ColrSet object for the colour magenta.

  • The text function is: colr.magenta.
  • The bg function is: colr.magentaBg.

[↑ Back to colr ↑]

cyan

colr.sets.cyan;

A ColrSet object for the colour cyan.

  • The text function is: colr.cyan.
  • The bg function is: colr.cyanBg.

[↑ Back to colr ↑]

white

colr.sets.white;

A ColrSet object for the colour white.

  • The text function is: colr.white.
  • The bg function is: colr.whiteBg.

[↑ Back to colr ↑]

black

colr.sets.black;

A ColrSet object for the colour black.

  • The text function is: colr.black.
  • The bg function is: colr.blackBg.

[↑ Back to colr ↑]

lightBlack

colr.sets.lightBlack;

A ColrSet object for the colour lightBlack.

  • The text function is: colr.lightBlack.
  • The bg function is: colr.lightBlackBg.

[↑ Back to colr ↑]

grey

colr.sets.grey;

A ColrSet object for the colour grey.

  • The text function is: colr.grey.
  • The bg function is: colr.greyBg.

[↑ Back to colr ↑]

gray

colr.sets.gray;

A ColrSet object for the colour gray.

  • The text function is: colr.gray.
  • The bg function is: colr.grayBg.

[↑ Back to colr ↑]

primary

colr.sets.primary;

A ColrSet object for the theme primary.

  • The text function is: colr.primary.
  • The bg function is: colr.primaryBg.

[↑ Back to colr ↑]

secondary

colr.sets.secondary;

A ColrSet object for the theme secondary.

  • The text function is: colr.secondary.
  • The bg function is: colr.secondaryBg.

[↑ Back to colr ↑]

success

colr.sets.success;

A ColrSet object for the theme success.

  • The text function is: colr.success.
  • The bg function is: colr.successBg.

[↑ Back to colr ↑]

danger

colr.sets.danger;

A ColrSet object for the theme danger.

  • The text function is: colr.danger.
  • The bg function is: colr.dangerBg.

[↑ Back to colr ↑]

warning

colr.sets.warning;

A ColrSet object for the theme warning.

  • The text function is: colr.warning.
  • The bg function is: colr.warningBg.

[↑ Back to colr ↑]

info

colr.sets.info;

A ColrSet object for the theme info.

  • The text function is: colr.info.
  • The bg function is: colr.infoBg.

[↑ Back to colr ↑]

WrapFn

Type for a function that manipulates a string

Can by a colr ColrFn, a chalk function, or something else

[↑ Back to colr ↑]

ColrFn

Type for a function that manipulates a string, but also has properties for chaining more colours/styles

See colr

[↑ Back to colr ↑]

WrapSet

An agnostic set of functions to wrap/modify the given text with the given colour/style.

Same as ColrSet, but not limited to colr library.

Has two properties:

  • text - A function to wrap/modify the given text with the given colour/style.
  • bg - A function to wrap/modify the background of the given text with the given colour/style.

Example:

const chalkSet: WrapSet = {
  text: chalk.redBright,
  bg: chalk.bgRedBright,
};

[↑ Back to colr ↑]

ColrSet

A set of ColrFns for a certain colour/theme.

Has two properties:

  • text - A function to set the text colour to the given colour/style.
  • bg - A function to set the background colour to the given colour/style.

[↑ Back to colr ↑]

table

A simple table generator

[↑ Back to top ↑]

print

table.print(body: any[][], header: any[][], options: TableOptions): number

Print a table

const header = [['Name', 'Age']];
const body = [['John', '25'], ['Jane', '26']];
table.print(body, header); // 7

// ┏━━━━━━┳━━━━━┓
// ┃ Name ┃ Age ┃
// ┡━━━━━━╇━━━━━┩
// │ John │ 25  │
// ├──────┼─────┤
// │ Jane │ 26  │
// └──────┴─────┘
# Parameter Name Required Type Default
0 body Yes any[][]
1 header No any[][]
2 options No TableOptions {}
Return Type
number

[↑ Back to table ↑]

printObjects

table.printObjects(objects: Object[], headers: Object, options: TableOptions): number

Print a table of given objects

const objs = [
  // objs
  { a: '1', b: '2', c: '3' },
  { a: '0', c: '2' },
  { b: '4' },
  { a: '6' }
];
const header = {
  a: 'Col A',
  b: 'Col B',
  c: 'Col C'
};
table.printObjects(objs, header); // 11

// ┏━━━━━━━┳━━━━━━━┳━━━━━━━┓
// ┃ Col A ┃ Col B ┃ Col C ┃
// ┡━━━━━━━╇━━━━━━━╇━━━━━━━┩
// │ 1     │ 2     │ 3     │
// ├───────┼───────┼───────┤
// │ 0     │       │ 2     │
// ├───────┼───────┼───────┤
// │       │ 4     │       │
// ├───────┼───────┼───────┤
// │ 6     │       │       │
// └───────┴───────┴───────┘
# Parameter Name Required Type Default
0 objects Yes Object[]
1 headers No Object {}
2 options No TableOptions {}
Return Type
number

[↑ Back to table ↑]

markdown

table.markdown(body: any[][], header: any[][], options: TableOptions): string[]

Generate a markdown table

const header = [['Name', 'Age (in years)', 'Job']];
const body = [
  ['Alexander', '25', 'Builder'],
  ['Jane', '26', 'Software Engineer']
];
const md = table.markdown(body, header, { alignCols: ['right', 'center', 'left'] });
console.log(md.join('\n'));

// |      Name | Age (in years) | Job               |
// |----------:|:--------------:|:------------------|
// | Alexander |       25       | Builder           |
// |      Jane |       26       | Software Engineer |
# Parameter Name Required Type Default
0 body Yes any[][]
1 header No any[][]
2 options No TableOptions {}
Return Type
string[]

[↑ Back to table ↑]

getLines

table.getLines(body: any[][], header: any[][], options: TableOptions): string[]

Get the lines of a table (rather than printing it)

const header = [['Name', 'Age']];
const body = [['John', '25'], ['Jane', '26']];
table.getLines(body, header);
// [
//   '┏━━━━━━┳━━━━━┓',
//   '┃ \x1B[1mName\x1B[22m ┃ \x1B[1mAge\x1B[22m ┃',
//   '┡━━━━━━╇━━━━━┩',
//   '│ John │ 25  │',
//   '├──────┼─────┤',
//   '│ Jane │ 26  │',
//   '└──────┴─────┘'
// ]
# Parameter Name Required Type Default
0 body Yes any[][]
1 header No any[][]
2 options No TableOptions {}
Return Type
string[]

[↑ Back to table ↑]

TableOptions

The configuration options for the table

[↑ Back to table ↑]

wrapperFn

Function to wrap each line of the output in (e.g. colr.blue)

[↑ Back to TableOptions ↑]

wrapLinesFn

Function to wrap the output lines of each cell of the table (e.g. colr.blue)

[↑ Back to TableOptions ↑]

wrapHeaderLinesFn

Function to wrap the output lines of each cell of the header of the table (e.g. colr.blue)

Default: colr.bold

[↑ Back to TableOptions ↑]

wrapBodyLinesFn

Function to wrap the output lines of each cell of the body of the table (e.g. colr.blue)

[↑ Back to TableOptions ↑]

overrideChar

Character to use instead of lines

Override character options are applied in the following order (later options have higher priority): overrideChar, overrideHorChar/overrideVerChar (see overridePrioritiseVer), overrideOuterChar, overrideCornChar, overrideCharSet

[↑ Back to TableOptions ↑]

overrideHorChar

Character to use instead of horizontal lines

Override character options are applied in the following order (later options have higher priority): overrideChar, overrideHorChar/overrideVerChar (see overridePrioritiseVer), overrideOuterChar, overrideCornChar, overrideCharSet

[↑ Back to TableOptions ↑]

overrideVerChar

Character to use instead of vertical lines

Override character options are applied in the following order (later options have higher priority): overrideChar, overrideHorChar/overrideVerChar (see overridePrioritiseVer), overrideOuterChar, overrideCornChar, overrideCharSet

[↑ Back to TableOptions ↑]

overrideCornChar

Character to use instead of corner and intersecting lines (┌, ┬, ┐, ├, ┼, ┤, └, ┴, ┘)

Override character options are applied in the following order (later options have higher priority): overrideChar, overrideHorChar/overrideVerChar (see overridePrioritiseVer), overrideOuterChar, overrideCornChar, overrideCharSet

[↑ Back to TableOptions ↑]

overrideOuterChar

Character to use instead of lines on the outside of the table (┌, ┬, ┐, ├, ┤, └, ┴, ┘)

Override character options are applied in the following order (later options have higher priority): overrideChar, overrideHorChar/overrideVerChar (see overridePrioritiseVer), overrideOuterChar, overrideCornChar, overrideCharSet

[↑ Back to TableOptions ↑]

overrideCharSet

Completely override all the characters used in the table.

See TableCharLookup for more information.

Default:

{
  hTop: ['━', '┏', '┳', '┓'],
  hNor: [' ', '┃', '┃', '┃'],
  hSep: ['━', '┣', '╋', '┫'],
  hBot: ['━', '┗', '┻', '┛'],
  mSep: ['━', '┡', '╇', '┩'],
  bTop: ['─', '┌', '┬', '┐'],
  bNor: [' ', '│', '│', '│'],
  bSep: ['─', '├', '┼', '┤'],
  bBot: ['─', '└', '┴', '┘']
}

[↑ Back to TableOptions ↑]

overridePrioritiseVer

By default, if not overrideHorChar and overrideVerChar are set, overrideHorChar will be prioritised (and used where both are applicable). Setting this to true will prioritise overrideVerChar instead.

Default: false

[↑ Back to TableOptions ↑]

drawOuter

Whether to draw the outer border of the table

[↑ Back to TableOptions ↑]

drawRowLines

Whether to draw lines between rows (other than separating header and body)

[↑ Back to TableOptions ↑]

drawColLines

Whether to draw lines between columns

[↑ Back to TableOptions ↑]

colWidths

Preferred width (in number of characters) of each column

[↑ Back to TableOptions ↑]

align

How the table should be aligned on the screen

left, right, center or justify

[↑ Back to TableOptions ↑]

alignCols

How each column should be aligned

Array with alignment for each column: left, right, center or justify

[↑ Back to TableOptions ↑]

transpose

Change rows into columns and vice versa

[↑ Back to TableOptions ↑]

transposeBody

Change rows into columns and vice versa (body only)

[↑ Back to TableOptions ↑]

margin

The amount of space to leave around the outside of the table

[↑ Back to TableOptions ↑]

cellPadding

The amount of space to leave around the outside of each cell

[↑ Back to TableOptions ↑]

format

A set of formatting configurations

[↑ Back to TableOptions ↑]

truncate

Truncates (cuts the end off) line instead of wrapping

[↑ Back to TableOptions ↑]

maxWidth

Maximum width of the table

[↑ Back to TableOptions ↑]

TableFormatConfig

Configuration for formatting a cell

[↑ Back to table ↑]

formatFn

A wrapper function to apply to the cell

[↑ Back to TableFormatConfig ↑]

isHeader

Whether to apply the format to the header

[↑ Back to TableFormatConfig ↑]

isBody

Whether to apply the format to the body

[↑ Back to TableFormatConfig ↑]

row

A specific row to apply the format to

[↑ Back to TableFormatConfig ↑]

col

A specific column to apply the format to

[↑ Back to TableFormatConfig ↑]

TableCharLookup

The configuration for the table line characters

Each property in the object represents a row type:

Type Description Example
hTop Lines at the top of the table, if there's a header ┏━━━┳━━━┓
hNor Regular lines of cells in a header cell ┃...┃...┃
hSep Lines between rows of the header ┣━━━╋━━━┫
hBot Lines at the bottom of the table, if there's a header but no body ┗━━━┻━━━┛
mSep Lines between the header and the body if both are there ┡━━━╇━━━┩
bTop Lines at the top of the table, if there's not a header ┌───┬───┐
bNor Regular lines of cells in a body cell │...│...│
bSep Lines between rows of the body ├───┼───┤
bBot Lines at the bottom of the table └───┴───┘

Each item in each array is a character to use for the row type:

Index Description Example
0 A regular character for the row (gets repeated for the width of the cell)
1 A border line at the start of the row
2 A border line between cells
3 A border line at the end of the row

[↑ Back to table ↑]

utils

objectsToTable

table.utils.objectsToTable(objects: Object[], headers: Object): { header: any[][]; body: any[][]; }

Process an array of objects into a table format (string[][])

const objs = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 26 }
];
table.utils.objectsToTable(objs)
// {
//   header: [ [ 'name', 'age' ] ],
//   body: [ [ 'John', 25 ], [ 'Jane', 26 ] ]
// }
# Parameter Name Required Type Default
0 objects Yes Object[]
1 headers No Object {}
Return Type
{ header: any[][]; body: any[][]; }

[↑ Back to table ↑]

transpose

table.utils.transpose(rows: any[][]): any[][]

Change rows into columns and vice versa

const input = [
  ['John', 25],
  ['Jane', 26],
  ['Derek', 27]
];
table.utils.transpose(input)
// [
//   [ 'John', 'Jane', 'Derek' ],
//   [ 25, 26, 27 ]
// ]
# Parameter Name Required Type
0 rows Yes any[][]
Return Type
any[][]

[↑ Back to table ↑]

concatRows

table.utils.concatRows(cells: { header: any[][]; body: any[][] }): any[][]

Concatenate header and body rows into one list of rows

const header = [['Name', 'Age']];
const body = [
  ['John', 25],
  ['Jane', 26],
  ['Derek', 27]
];
table.utils.concatRows({header, body})
// [
//   [ 'Name', 'Age' ],
//   [ 'John', 25 ],
//   [ 'Jane', 26 ],
//   [ 'Derek', 27 ]
// ]
# Parameter Name Required Type
0 cells Yes { header: any[][]; body: any[][] }
Return Type
any[][]

[↑ Back to table ↑]

getFormat

table.utils.getFormat(format: WrapFn, row: number, col: number, isHeader: boolean, isBody: boolean): TableFormatConfig

A function for simplifying the format configuration

const wrap = (str: string) => 'X';

const format = [table.utils.getFormat(wrap, 0, 0), table.utils.getFormat(wrap, 1, 1, false, true), table.utils.getFormat(wrap, 2, 2, true, false)];
// [
//   { formatFn: wrap, row: 0, col: 0 },
//   { formatFn: wrap, row: 1, col: 1, isHeader: false, isBody: true },
//   { formatFn: wrap, row: 2, col: 2, isHeader: true, isBody: false }
// ]

const header = partition(range(9), 3);
const body = partition(range(9), 3);
table.print(header, body, {format})
// ┏━━━┳━━━┳━━━┓
// ┃ 0 ┃ 1 ┃ 2 ┃
// ┣━━━╋━━━╋━━━┫
// ┃ 3 ┃ 4 ┃ 5 ┃
// ┣━━━╋━━━╋━━━┫
// ┃ 6 ┃ 7 ┃ X ┃
// ┡━━━╇━━━╇━━━┩
// │ X │ 1 │ 2 │
// ├───┼───┼───┤
// │ 3 │ X │ 5 │
// ├───┼───┼───┤
// │ 6 │ 7 │ 8 │
// └───┴───┴───┘
# Parameter Name Required Type
0 format Yes WrapFn
1 row No number
2 col No number
3 isHeader No boolean
4 isBody No boolean
Return Type
TableFormatConfig

[↑ Back to table ↑]

getFullOptions

table.utils.getFullOptions(opts: TableOptions): FullTableOptions

A function for simplifying the format configuration

# Parameter Name Required Type
0 opts Yes TableOptions
Return Type
FullTableOptions

[↑ Back to table ↑]

Logger

[↑ Back to top ↑]

log

log;

A set of log functions

log.blank('This is blank');     //                       This is blank
log.log('This is log');         // [12:00:00.123]  LOG   This is log
log.out('This is out');         // [12:00:00.123]  OUT   This is out
log.normal('This is normal');   // [12:00:00.123]  LOG   This is normal
log.verbose('This is verbose'); // [12:00:00.123]  LOG   This is verbose
log.debug('This is debug');     // [12:00:00.123]  DBUG  This is debug
log.info('This is info');       // [12:00:00.123]  INFO  This is info
log.warn('This is warn');       // [12:00:00.123]  WARN  This is warn
log.error('This is error');     // [12:00:00.123]  ERRR  This is error

[↑ Back to Logger ↑]

LogTools

A collection of tools for logging

[↑ Back to top ↑]

getLogStr

LogTools.getLogStr(item: any): string
getLogStr(item: any): string

Get a string for a given object as it would be printed by console.log

getLogStr(true); // true
getLogStr(1); // 1
getLogStr('foobar'); // foobar
getLogStr({ test: 'test' }); // { test: 'test' }
getLogStr(['a', 'b', 'c']); // [ 'a', 'b', 'c' ]

getLogStr([
  [
    [
      ['a', 'b', 'c'],
      ['d', 'e', 'f']
    ],
    [
      ['g', 'h', 'i'],
      ['j', 'k', 'l']
    ]
  ],
  [
    [
      ['m', 'n', 'o']
    ]
  ]
]);
// [
//   [
//     [ [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ] ],
//     [ [ 'g', 'h', 'i' ], [ 'j', 'k', 'l' ] ]
//   ],
//   [ [ [ 'm', 'n', 'o' ] ] ]
// ]
# Parameter Name Required Type
0 item Yes any
Return Type
string

[↑ Back to LogTools ↑]

processLogContents

LogTools.processLogContents(prefix: string, wrapper: Function, ...args: any[]): string
processLogContents(prefix: string, wrapper: Function, ...args: any[]): string

Process an item to be logged

# Parameter Name Required Type Default
0 prefix Yes string
1 wrapper No Function fn.noact
2… args No any[]
Return Type
string

[↑ Back to LogTools ↑]

getLog

LogTools.getLog(prefix: string, wrapper: Function): (...args: any[]) => void
getLog(prefix: string, wrapper: Function): (...args: any[]) => void

Get a log function for a given prefix

# Parameter Name Required Type Default
0 prefix Yes string
1 wrapper No Function fn.noact
Return Type
(...args: any[]) => void

[↑ Back to LogTools ↑]

createLogger

createLogger(extraConfigs: T, options: LogOptions): Logger<T>

Create a logger with custom configs

const log = createLogger({
  myLog: {
    name: 'MYLOG',
    nameColour: colr.dark.magenta,
    showDate: false,
    showTime: true,
    contentColour: colr.yellow
  }
});

log.myLog('Hello World'); // [12:00:00.123]  MYLOG  Hello World
# Parameter Name Required Type Default
0 extraConfigs No T {} as T
1 options No LogOptions {}
Return Type
Logger<T>

[↑ Back to LogTools ↑]

LogOptions

LogOptions;

Options for the log function

[↑ Back to LogTools ↑]

LogConfig

LogConfig;

Configuration for the log function

See createLogger

[↑ Back to LogTools ↑]

PathTools

A collection of tools for working with paths

[↑ Back to top ↑]

explodePath

PathTools.explodePath(path: string): ExplodedPath
explodePath(path: string): ExplodedPath

'Explodes' a path into its components

  • path: the full original path as it was passed in.
  • dir: the directory path of the given path
  • name: the name of the file, not including the extension
  • ext: the extension of the file, not including the dot
  • filename: the full name of the file, including the extension (and dot)
  • folders: the ancestral folders of the given dir as an array
const { dir, name, ext, filename } = explodePath('/path/to/file.txt');

console.log(path); // '/path/to/file.txt'
console.log(dir); // '/path/to'
console.log(name); // 'file'
console.log(ext); // 'txt'
console.log(filename); // 'file.txt'
console.log(folders); // ['path', 'to']
# Parameter Name Required Type
0 path Yes string
Return Type
ExplodedPath

[↑ Back to PathTools ↑]

ExplodedPath

PathTools.ExplodedPath;
ExplodedPath;

An object containing the exploded components of a path

See explodePath for more details

[↑ Back to PathTools ↑]

path

The full original path as it was passed in.

[↑ Back to ExplodedPath ↑]

dir

The directory path of the given path

Note: no trailing slash

[↑ Back to ExplodedPath ↑]

folders

the ancestral folders of the given dir as an array

[↑ Back to ExplodedPath ↑]

name

the name of the file, not including the extension

[↑ Back to ExplodedPath ↑]

ext

the extension of the file, not including the dot

[↑ Back to ExplodedPath ↑]

filename

the full name of the file, including the extension (and dot)

[↑ Back to ExplodedPath ↑]

removeTrailSlash

PathTools.removeTrailSlash(path: string): string

Remove trailing slash from path (if one exists)

'/path/to/file/' -> '/path/to/file'
# Parameter Name Required Type
0 path Yes string
Return Type
string

[↑ Back to PathTools ↑]

trailSlash

PathTools.trailSlash(path: string): string

Ensures there's a trailing slash on path

'/path/to/file' -> '/path/to/file/'
# Parameter Name Required Type
0 path Yes string
Return Type
string

[↑ Back to PathTools ↑]

removeDoubleSlashes

PathTools.removeDoubleSlashes(path: string): string

Removes double slashes from path (an bug with Unix paths)

'/path/to//file' -> '/path/to/file'
# Parameter Name Required Type
0 path Yes string
Return Type
string

[↑ Back to PathTools ↑]

progressBarTools

A collection of tools for working with progress bars (from swiss-ak)

[↑ Back to top ↑]

getColouredProgressBarOpts

progressBarTools.getColouredProgressBarOpts(opts: pr

Readme

Keywords

none

Package Sidebar

Install

npm i swiss-node

Weekly Downloads

7

Version

3.1.4

License

MIT

Unpacked Size

1.99 MB

Total Files

77

Last publish

Collaborators

  • jackcannon