New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

swiss-node

Package Overview
Dependencies
Maintainers
1
Versions
30
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

swiss-node

Swiss Army Knife for node

  • 3.0.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
4
decreased by-82.61%
Maintainers
1
Weekly downloads
 
Created
Source

swiss-node

Swiss Army Knife for node

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

Uses swiss-ak

  • Table of Contents

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 NameRequiredType
0questionYesstring | Breadcrumb
1initialNostring
2validateNo(value: string) => Error | string | boolean | void
3lcNoLineCounter
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 NameRequiredType
0questionYesstring | Breadcrumb
1choicesYesask.PromptChoice<T>[]
2initialNoT | string
3validateNo(item: T, index: number, typedValue: string) => Error | string | boolean | void
4lcNoLineCounter
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 NameRequiredType
0questionYesstring | Breadcrumb
1initialNonumber
2validateNo(value: number) => Error | string | boolean | void
3lcNoLineCounter
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 NameRequiredTypeDefault
0questionYesstring | Breadcrumb
1initialNobooleantrue
2validateNo(value: boolean) => Error | string | boolean | void
3lcNoLineCounter
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 NameRequiredType
0questionYesstring | Breadcrumb
1validateNo(value: boolean) => Error | string | boolean | void
2lcNoLineCounter
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 NameRequiredType
0questionYesstring | Breadcrumb
1choicesYesask.PromptChoice<T>[]
2initialNoask.PromptChoice<T> | number
3validateNo(item: T, index: number) => Error | string | boolean | void
4lcNoLineCounter
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 NameRequiredType
0questionYesstring | Breadcrumb
1choicesYesask.PromptChoice<T>[]
2initialNoask.PromptChoice<T> | ask.PromptChoice<T>[] | number | number[]
3validateNo(items: T[], indexes: number[]) => Error | string | boolean | void
4lcNoLineCounter
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 NameRequiredType
0questionTextNostring | Breadcrumb
1initialNoDate
2validateNo(date: Date) => Error | string | boolean | void
3lcNoLineCounter
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 NameRequiredType
0questionTextNostring | Breadcrumb
1initialNoDate
2validateNo(date: Date) => Error | string | boolean | void
3lcNoLineCounter
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 NameRequiredType
0questionTextNostring | Breadcrumb
1initialNoDate
2validateNo(date: Date) => Error | string | boolean | void
3lcNoLineCounter
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 NameRequiredType
0questionTextNostring | Breadcrumb
1initialStartNoDate
2initialEndNoDate
3validateNo(dates: [Date, Date]) => Error | string | boolean | void
4lcNoLineCounter
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): 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 NameRequiredTypeDefault
0questionTextYesstring | Breadcrumb
1selectTypeNo'd' | 'f''f'
2startPathNostringprocess.cwd()
3validateNo(path: string) => Error | string | boolean | void
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): 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 NameRequiredTypeDefault
0questionTextYesstring | Breadcrumb
1selectTypeNo'd' | 'f''f'
2startPathNostringprocess.cwd()
3validateNo(paths: string[]) => Error | string | boolean | void
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 NameRequiredTypeDefault
0questionTextYesstring | Breadcrumb
1startPathNostringprocess.cwd()
2suggestedFileNameNostring''
3validateNo(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 NameRequiredTypeDefault
0questionYesstring | Breadcrumb
1itemsYesT[]
2settingsNoAskTableDisplaySettings<T>{}
3initialNoT | number
4validateNo(item: T) => Error | string | boolean | void
5lcNoLineCounter
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);
┏━━━┳━━━━━━━┳━━━━━┓
┃   ┃ NameAge ┃
┡━━━╇━━━━━━━╇━━━━━┩
│ ◉ │ John25  │
├───┼───────┼─────┤
│ ◯ │ Jane26  │
├───┼───────┼─────┤
│ ◉ │ Derek27  │
└───┴───────┴─────┘
// [
//   { name: 'John', age: 25 },
//   { name: 'Derek', age: 27 }
// ]
#Parameter NameRequiredTypeDefault
0questionYesstring | Breadcrumb
1itemsYesT[]
2settingsNoAskTableDisplaySettings<T>{}
3initialNoT[] | number[]
4validateNo(items: T[]) => Error | string | boolean | void
5lcNoLineCounter
Return Type
Promise<T[]>

[↑ Back to ask ↑]

AskTableDisplaySettings
AskTableDisplaySettings<T>;

Settings for how the table should display the items

All settings are optional.

NameTypeDescription
rowsany[][] | (item: T) => any[]Rows to display or function that takes an item and returns a row
headersany[][] | RemapOf<T, string>Header to display, or object with title for each item property
optionstable.TableOptionsOptions 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 NameRequiredTypeDefault
0questionYesstring | Breadcrumb
1totalFramesYesnumber
2frameRateNonumber60
3initialNoPartial<Handles<number>>
4validateNo(handles: Handles<number>) => Error | string | boolean | void
5lcNoLineCounter
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 NameRequiredType
0optionsYesPartial<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 NameRequiredTypeDefault
0questionYesstring | Breadcrumb
1isCompleteNobooleanfalse
2isErrorNobooleanfalse
3lcNoLineCounter
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 NameRequiredType
0totalSecondsYesnumber
1templateNo(s: second) => string
2isCompleteNoboolean
3isErrorNoboolean
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 NameRequiredTypeDefault
0textNostring | 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 NameRequiredTypeDefault
0questionYesstring | Breadcrumb
1resultNoany
2isCompleteNobooleantrue
3isErrorNobooleanfalse
4errorMessageNostring
5lcNoLineCounter
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 NameRequiredType
0questionYesstring | Breadcrumb
1valueYesT | undefined
2askFnYes(question: string | Breadcrumb, lc: LineCounter) => Promise<T> | T
3lcNoLineCounter
Return Type
Promise<T>

[↑ Back to ask ↑]

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

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 NameRequiredTypeDefault
0startObjNoPartial<T>{}
Return Type
any

[↑ 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 NameRequiredType
0questionYesstring | Breadcrumb
1sectionHeaderNo(lc: LineCounter) => void | Promise<any>
2…questionFnsNo[...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 NameRequiredTypeDefault
0versionNo'down' | 'none' | 'up''down'
1spacingNonumber8
2offsetNonumber0
3widthNonumberout.utils.getTerminalWidth() - 2
4lcNoLineCounter
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 NameRequiredTypeDefault
0itemsYesT[]
1titlesNostring[][]
2titleFnNoTitleFn<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

NameTypeDescription
themeColourstring (Colour)Set the main theme colour
lcLineCounterA line counter that all ask prompts will add to when complete
boxType'thin' | 'thick'What type of box drawing lines to use
beepsbooleanWhether to make an audio beeps when appropriate
maxItemsOnScreennumberHow many select/multiselect items to have on screen at most
scrollMarginnumberHow much space to leaving when 'scrolling' lists of items
fileExplorerColumnWidthnumberHow wide to make each panel of the fileExplorer interface
fileExplorerMaxItemsnumberHow many items to show in each panel of the fileExplorer interface
tableSelectMaxHeightPercentagenumberPercent of terminal height to use at max for table selects
timelineSpeednumberHow many frames to move on a timeline at a time
timelineFastSpeednumberHow 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

NameTypeDescription
boolTrueKeysstringWhat buttons to use to indicate true for boolean prompts
boolFalseKeysstringWhat buttons to use to indicate false for boolean prompts
boolYesstring'Yes'
boolNostring'No'
boolYesNoSeparatorstring'/'
boolYNstring'(Y/n)'
selectAllstring'[Select All]'
donestring'done'
items(num: number) => string'[X items]'
countdown(secs: number) => string'Starting in Xs...'
filestring'File'
directorystring'Directory'
loadingstring'Loading...'
selected(num: number) => string'X selected'
specialNewFolderEnterNothingCancelstring'Enter nothing to cancel'
specialNewFolderAddingFolderTostring'Adding folder to '
specialNewFolderQuestion(hl: any) => string'What do you want to name the new folder?'
specialSaveFileSavingFileTostring'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.

NameDescription
decorationGeneral decoration and cosmetics
questionTextThe text of the question of the prompt
specialIconSpecial icon for the 'state'
openingIconThe initial/opening icon
promptIconThe icon that indicates where you are typing
resultGeneral result
resultTextString results
resultNumberNumber results
resultBooleanBoolean results
resultArrayArray results
resultDateDate results
loadingIconIcon for ask.loading
errorMsgThe error message (if there is one)
itemA normal item in a list
itemIconIcon for a normal item in a list
itemHoverA hovered item in a list
itemHoverIconIcon for a hovered item in a list
itemBlockHoverA hovered item in a list (block mode)
itemBlockHoverIconIcon for a hovered item in a list (block mode)
itemSelectedA selected item in a list
itemSelectedIconIcon for a selected item in a list
itemUnselectedAn unselected item in a list
itemUnselectedIconIcon for an unselected item in a list
scrollbarTrackThe track for the scrollbar
scrollbarBarThe bar for the scrollbar
selectAllText'Select All' item in a multi-select
boolYNTextThe '(Y/n)' bit for the booleanYN prompt
countdownask.countdown
pauseask.pause
specialHoverThe focus of what the user is controlling (for dates, fileExplorer, etc)
specialSelectedSomething that has been selected (for dates, fileExplorer, etc)
specialHighlightMore important that normal (e.g. date within a range) (for dates, fileExplorer, etc)
specialNormalNormal items (for dates, fileExplorer, etc)
specialFadedNot important (for dates, fileExplorer, etc)
specialHintHints/tips/advice (for dates, fileExplorer, etc)
specialInactiveHoverThe focus of what the user is controlling (Inactive) (for dates, fileExplorer, etc)
specialInactiveSelectedSomething that has been selected (Inactive) (for dates, fileExplorer, etc)
specialInactiveHighlightMore important that normal (e.g. date within a range) (Inactive) (for dates, fileExplorer, etc)
specialInactiveNormalNormal items (Inactive) (for dates, fileExplorer, etc)
specialInactiveFadedNot important (Inactive) (for dates, fileExplorer, etc)
specialInactiveHintHints/tips/advice (Inactive) (for dates, fileExplorer, etc)
specialInfoAction bar at bottom (for dates, fileExplorer, etc)
specialErrorMsgError messages (for dates, fileExplorer, etc)
specialErrorIconIcon for errors (for dates, fileExplorer, etc)
tableSelectHoverHover for table selects only (shouldn't be 'block'/bg styles)
timelineTrackThe (inactive) track of a timeline
timelineTrackActiveThe active track of a timeline
timelineHandleThe (inactive) control handle on a timeline
timelineHandleActiveThe 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.

NameDescription
specialIconSpecial icon for the 'state'
openingIconThe initial/opening icon
promptIconThe icon that indicates where you are typing
errorMsgPrefixIcon shown before error messages
itemIconIcon for a normal item in a list
itemHoverIconIcon for a hovered item in a list
itemSelectedIconIcon for a selected item in a list
itemUnselectedIconIcon for an unselected item in a list
scrollUpIconUsed to indicate you can scroll up
scrollDownIconUsed to indicate you can scroll down
scrollbarTrackThe track part of the scrollbar
scrollbarTrackTrimTopThe trimmed top of the track (half height)
scrollbarTrackTrimBottomThe trimmed bottom of the track (half height)
scrollbarBarThe bar part of the scrollbar
scrollbarBarTrimTopThe trimmed top of the bar (half height)
scrollbarBarTrimBottomThe trimmed bottom of the bar (half height)
separatorLineLine added by ask.separator
separatorNodeDownNode is ask.separator line that indicates 'down'
separatorNodeNoneNode is ask.separator line that breaks up the pattern
separatorNodeUpNode is ask.separator line that indicates 'up'
specialErrorIconIcon for errors (for dates, fileExplorer, etc)
folderOpenableIconShown at end of line for folders to show they can be opened (right-wards)
fileOpenableIconFile version of folderOpenableIcon. Typically empty
timelineTrackThe track of a timeline
timelineHandleThe control handle on a timeline
timelineBarThe '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 NameRequiredType
0textYesstring
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 NameRequiredTypeDefault
0lineYesstring
1startYesnumber
2endYesnumber
3replaceCharNostring' '
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 NameRequiredTypeDefault
0itemYesany
1widthNonumberout.utils.getTerminalWidth()
2replaceCharNostring' '
3forceWidthNobooleantrue
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 NameRequiredTypeDefault
0itemYesany
1widthNonumberout.utils.getTerminalWidth()
2replaceCharNostring' '
3forceWidthNobooleantrue
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 NameRequiredTypeDefault
0itemYesany
1widthNonumberout.utils.getTerminalWidth()
2replaceCharNostring' '
3forceWidthNobooleantrue
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 NameRequiredTypeDefault
0itemYesany
1widthNonumberout.utils.getTerminalWidth()
2replaceCharNostring' '
3forceWidthNobooleantrue
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 NameRequiredTypeDefault
0linesYesstring[]
1widthNonumbergetLongestLen(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 NameRequiredTypeDefault
0linesYesstring[]
1widthNonumbergetLongestLen(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 NameRequiredTypeDefault
0linesYesstring[]
1widthNonumbergetLongestLen(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 NameRequiredTypeDefault
0linesYesstring[]
1widthNonumbergetLongestLen(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 NameRequiredTypeDefault
0itemYesany
1directionYesAlignType
2widthNonumberout.utils.getTerminalWidth()
3replaceCharNostring' '
4forceWidthNobooleantrue
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 NameRequiredTypeDefault
0leftItemYesany
1rightItemYesany
2widthNonumberout.utils.getTerminalWidth()
3replaceCharNostring' '
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 NameRequiredTypeDefault
0itemYesany
1widthNonumberout.utils.getTerminalWidth()
2alignmentNoAlignType
3forceWidthNobooleanfalse
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 NameRequiredTypeDefault
0linesNonumber1
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 NameRequiredTypeDefault
0actionNo(s: string) => string | voidloadingDefault
1linesNonumber1
2symbolsNostring[]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 NameRequiredType
0textYesstring
1maxLengthYesnumber
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 NameRequiredType
0textYesstring
1maxLengthYesnumber
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 NameRequiredTypeDefault
0textYesstring
1maxLengthNonumberout.utils.getTerminalWidth()
2suffixNostringcolr.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 NameRequiredTypeDefault
0textYesstring
1maxLengthNonumberout.utils.getTerminalWidth()
2suffixNostringcolr.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 NameRequiredType
0…groupsNostring[][]
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 NameRequiredType
0optionsYesResponsiveOption<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 NameRequiredTypeDefaultDescription
0xNonumber0The x position to move the cursor to
1yNonumber0The y position to move the cursor to
Return Type
stringescape 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 NameRequiredTypeDefaultDescription
0xNonumber0How many spaces to move the cursor horizontally (negative values move left)
1yNonumber0How many spaces to move the cursor vertically (negative values move up)
Return Type
stringescape 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 NameRequiredTypeDefaultDescription
0countNonumber1How many spaces to move the cursor up
Return Type
stringescape 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 NameRequiredTypeDefaultDescription
0countNonumber1How many spaces to move the cursor down
Return Type
stringescape 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 NameRequiredTypeDefaultDescription
0countNonumber1How many spaces to move the cursor left
Return Type
stringescape 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 NameRequiredTypeDefaultDescription
0countNonumber1How many spaces to move the cursor right
Return Type
stringescape 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 NameRequiredTypeDefaultDescription
0countNonumber1How many lines to move the cursor down
Return Type
stringescape 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 NameRequiredTypeDefaultDescription
0countNonumber1How many lines to move the cursor up
Return Type
stringescape 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 NameRequiredTypeDescription
0isShowYesbooleanWhether or not the cursor should be shown
Return Type
stringescape 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 NameRequiredTypeDefaultDescription
0countNonumber1How much to scroll the terminal up by
Return Type
stringescape 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 NameRequiredTypeDefaultDescription
0countNonumber1How much to scroll the terminal down by
Return Type
stringescape 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 NameRequiredTypeDefaultDescription
0countNonumber1How many lines to erase
Return Type
stringescape 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 NameRequiredTypeDefaultDescription
0countNonumber1How many lines to erase
Return Type
stringescape 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 NameRequiredTypeDefaultDescription
0countNonumber1How many lines to erase
Return Type
stringescape 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 NameRequiredTypeDefaultDescription
0countNonumber1How many lines to reserve
Return Type
stringescape 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 NameRequiredType
0…baseNamesNostring[]
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 NameRequiredTypeDescription
0…argsYesany[]The arguments to log
Return Type
numbernumber 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 NameRequiredTypeDescription
0…argsYesany[]The arguments to overwrite
Return Type
numbernumber 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 NameRequiredTypeDescription
0newLinesYesnumberThe number of lines to add
1funcYes(...args: A[]) => number | TThe function to wrap
2…argsYesA[]The arguments to pass to the function
Return Type
Tresult of the function

[↑ Back to getLineCounter ↑]

lc.add

Adds a given number to the line counter

const lc = getLineCounter();
lc.add(1);
#Parameter NameRequiredTypeDescription
0newLinesYesnumberThe 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
numberline 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 NameRequiredTypeDescription
0checkpointIDYesstringThe checkpoint to check
Return Type
numbernumber 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 NameRequiredTypeDescription
0yYesnumberHow 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 NameRequiredTypeDescription
0checkpointIDYesstringThe 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 NameRequiredTypeDescription
0linesToMoveBackYesnumberThe number of lines to clear
1limitToRecordedLinesNobooleanWhether 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 NameRequiredTypeDescription
0linesYesnumberThe 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 NameRequiredTypeDescription
0checkpointIDNostringThe checkpoint to record
Return Type
stringcheckpointID

[↑ 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 NameRequiredTypeDescription
0checkpointIDYesstringThe 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 NameRequiredTypeDescription
0yYesnumberHow 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 NameRequiredTypeDescription
0checkpointIDYesstringThe 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 NameRequiredTypeDescription
0linesToMoveBackYesnumberThe number of lines to clear
1limitToRecordedLinesNobooleanWhether 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 NameRequiredTypeDescription
0linesYesnumberThe 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 NameRequiredTypeDescription
0checkpointIDYesstringThe 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 NameRequiredType
0textYesText
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 NameRequiredType
0textYesText
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 NameRequiredType
0textYesText
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 NameRequiredType
0itemYesany
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 NameRequiredType
0itemYesText
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 NameRequiredType
0itemYesText
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 NameRequiredType
0linesYesstring[]
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 NameRequiredType
0strYesstring
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 NameRequiredType
0textYesstring
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 NameRequiredTypeDefault
0flagsNostring'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.

NameTypeModifierDescription
lightTextLightcolr.light()Use light text colours (on by default)
darkTextDarkcolr.dark()Use dark text colours
lightBgBackgroundLightcolr.lightBg()Use light background colours (on by default)
darkBgBackgroundDarkcolr.darkBg()Use dark background colours
NameAffectsColourTypeRecommendedAlt
redText🟥 RedBase (Light)colr.red()
darkRedText🟥 RedDarkcolr.dark.red()colr.darkRed()
lightRedText🟥 RedLightcolr.light.red()colr.lightRed()
greenText🟩 GreenBase (Light)colr.green()
darkGreenText🟩 GreenDarkcolr.dark.green()colr.darkGreen()
lightGreenText🟩 GreenLightcolr.light.green()colr.lightGreen()
yellowText🟨 YellowBase (Light)colr.yellow()
darkYellowText🟨 YellowDarkcolr.dark.yellow()colr.darkYellow()
lightYellowText🟨 YellowLightcolr.light.yellow()colr.lightYellow()
blueText🟦 BlueBase (Light)colr.blue()
darkBlueText🟦 BlueDarkcolr.dark.blue()colr.darkBlue()
lightBlueText🟦 BlueLightcolr.light.blue()colr.lightBlue()
magentaText🟪 MagentaBase (Light)colr.magenta()
darkMagentaText🟪 MagentaDarkcolr.dark.magenta()colr.darkMagenta()
lightMagentaText🟪 MagentaLightcolr.light.magenta()colr.lightMagenta()
cyanText💠 CyanBase (Light)colr.cyan()
darkCyanText💠 CyanDarkcolr.dark.cyan()colr.darkCyan()
lightCyanText💠 CyanLightcolr.light.cyan()colr.lightCyan()
whiteText⬜ WhiteBase (Light)colr.white()
darkWhiteText⬜ WhiteDarkcolr.dark.white()colr.darkWhite()
lightWhiteText⬜ WhiteLightcolr.light.white()colr.lightWhite()
redBgBackground🟥 RedBase (Light)colr.redBg()
darkRedBgBackground🟥 RedDarkcolr.darkBg.redBg()colr.darkRedBg()
lightRedBgBackground🟥 RedLightcolr.lightBg.redBg()colr.lightRedBg()
greenBgBackground🟩 GreenBase (Light)colr.greenBg()
darkGreenBgBackground🟩 GreenDarkcolr.darkBg.greenBg()colr.darkGreenBg()
lightGreenBgBackground🟩 GreenLightcolr.lightBg.greenBg()colr.lightGreenBg()
yellowBgBackground🟨 YellowBase (Light)colr.yellowBg()
darkYellowBgBackground🟨 YellowDarkcolr.darkBg.yellowBg()colr.darkYellowBg()
lightYellowBgBackground🟨 YellowLightcolr.lightBg.yellowBg()colr.lightYellowBg()
blueBgBackground🟦 BlueBase (Light)colr.blueBg()
darkBlueBgBackground🟦 BlueDarkcolr.darkBg.blueBg()colr.darkBlueBg()
lightBlueBgBackground🟦 BlueLightcolr.lightBg.blueBg()colr.lightBlueBg()
magentaBgBackground🟪 MagentaBase (Light)colr.magentaBg()
darkMagentaBgBackground🟪 MagentaDarkcolr.darkBg.magentaBg()colr.darkMagentaBg()
lightMagentaBgBackground🟪 MagentaLightcolr.lightBg.magentaBg()colr.lightMagentaBg()
cyanBgBackground💠 CyanBase (Light)colr.cyanBg()
darkCyanBgBackground💠 CyanDarkcolr.darkBg.cyanBg()colr.darkCyanBg()
lightCyanBgBackground💠 CyanLightcolr.lightBg.cyanBg()colr.lightCyanBg()
whiteBgBackground⬜ WhiteBase (Light)colr.whiteBg()
darkWhiteBgBackground⬜ WhiteDarkcolr.darkBg.whiteBg()colr.darkWhiteBg()
lightWhiteBgBackground⬜ WhiteLightcolr.lightBg.whiteBg()colr.lightWhiteBg()
blackText⬛ BlackAlways Darkcolr.black()
darkBlackText⬛ BlackDarkcolr.black()colr.darkBlack()
lightBlackText⬛ BlackLightcolr.light.black()colr.lightBlack()
blackBgBackground⬛ BlackAlways Darkcolr.blackBg()
darkBlackBgBackground⬛ BlackDarkcolr.blackBg()colr.darkBlackBg()
lightBlackBgBackground⬛ BlackLightcolr.lightBg.blackBg()colr.lightBlackBg()
greyText🩶 GreyGreyscolr.grey()
greyBgBackground🩶 GreyGreyscolr.greyBg()
grey0Text⬛ BlackGreyscolr.grey0()
grey1Text🩶 GreyGreyscolr.grey1()
grey2Text🩶 GreyGreyscolr.grey2()
grey3Text🩶 GreyGreyscolr.grey3()
grey4Text🩶 GreyGreyscolr.grey4()
grey5Text⬜ WhiteGreyscolr.grey5()
primaryText🟨 YellowThemecolr.primary()
secondaryText🟪 MagentaThemecolr.secondary()
successText🟩 GreenThemecolr.success()
dangerText🟥 RedThemecolr.danger()
warningText🟨 YellowThemecolr.warning()
infoText🟦 BlueThemecolr.info()
primaryBgBackground🟨 YellowThemecolr.primaryBg()
secondaryBgBackground🟪 MagentaThemecolr.secondaryBg()
successBgBackground🟩 GreenThemecolr.successBg()
dangerBgBackground🟥 RedThemecolr.dangerBg()
warningBgBackground🟨 YellowThemecolr.warningBg()
infoBgBackground🟦 BlueThemecolr.infoBg()
NameDescription
resetcolr.reset('')This returns the text back to normal colours/styles
boldcolr.bold('')This makes the text bold
dimcolr.dim('')This dims the brightness of the text colour
italiccolr.italic('')This makes the text italic
overlinecolr.overline('')This adds a horizontal line above the text
underlinecolr.underline('')This adds a horizontal line below the text
strikethroughcolr.strikethrough('')This add a horizontal line through the middle of the given text
inversecolr.inverse('')This inverses the text and background colours for the given text
hiddencolr.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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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 NameRequiredType
0…textYesstring[]
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.
ColourLight TextDark TextLight BGDark 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.

Nametextbg
redcolr.redcolr.redBg
greencolr.greencolr.greenBg
yellowcolr.yellowcolr.yellowBg
bluecolr.bluecolr.blueBg
magentacolr.magentacolr.magentaBg
cyancolr.cyancolr.cyanBg
whitecolr.whitecolr.whiteBg
blackcolr.blackcolr.blackBg
lightBlackcolr.lightBlackcolr.lightBlackBg
greycolr.greycolr.greyBg
graycolr.graycolr.grayBg
primarycolr.primarycolr.primaryBg
secondarycolr.secondarycolr.secondaryBg
successcolr.successcolr.successBg
dangercolr.dangercolr.dangerBg
warningcolr.warningcolr.warningBg
infocolr.infocolr.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 NameRequiredTypeDefault
0bodyYesany[][]
1headerNoany[][]
2optionsNoTableOptions{}
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 NameRequiredTypeDefault
0objectsYesObject[]
1headersNoObject{}
2optionsNoTableOptions{}
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 NameRequiredTypeDefault
0bodyYesany[][]
1headerNoany[][]
2optionsNoTableOptions{}
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 NameRequiredTypeDefault
0bodyYesany[][]
1headerNoany[][]
2optionsNoTableOptions{}
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:

TypeDescriptionExample
hTopLines at the top of the table, if there's a header┏━━━┳━━━┓
hNorRegular lines of cells in a header cell┃...┃...┃
hSepLines between rows of the header┣━━━╋━━━┫
hBotLines at the bottom of the table, if there's a header but no body┗━━━┻━━━┛
mSepLines between the header and the body if both are there┡━━━╇━━━┩
bTopLines at the top of the table, if there's not a header┌───┬───┐
bNorRegular lines of cells in a body cell│...│...│
bSepLines between rows of the body├───┼───┤
bBotLines at the bottom of the table└───┴───┘

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

IndexDescriptionExample
0A regular character for the row (gets repeated for the width of the cell)
1A border line at the start of the row
2A border line between cells
3A 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 NameRequiredTypeDefault
0objectsYesObject[]
1headersNoObject{}
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 NameRequiredType
0rowsYesany[][]
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 NameRequiredType
0cellsYes{ 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 NameRequiredType
0formatYesWrapFn
1rowNonumber
2colNonumber
3isHeaderNoboolean
4isBodyNoboolean
Return Type
TableFormatConfig

[↑ Back to table ↑]

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

A function for simplifying the format configuration

#Parameter NameRequiredType
0optsYesTableOptions
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 NameRequiredType
0itemYesany
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 NameRequiredTypeDefault
0prefixYesstring
1wrapperNoFunctionfn.noact
2…argsNoany[]
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 NameRequiredTypeDefault
0prefixYesstring
1wrapperNoFunctionfn.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 NameRequiredTypeDefault
0extraConfigsNoT{} as T
1optionsNoLogOptions{}
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 NameRequiredType
0pathYesstring
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 NameRequiredType
0pathYesstring
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 NameRequiredType
0pathYesstring
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 NameRequiredType
0pathYesstring
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: progressBar.ProgressBarOptions, randomise: boolean): (prefix?: string, override?: any, resetColours?: boolean) => any

Helper for providing a consistent set of options for a progress bar, and colouring them appropriately

const progOpts = progressBarTools.getColouredProgressBarOpts({
  showCount: true,
  showPercent: true,
});
// later...
const progressBar = getProgressBar(numThings, progOpts('Things'));
progressBar.update();
#Parameter NameRequiredTypeDefault
0optsYesprogressBar.ProgressBarOptions
1randomiseNobooleanfalse
Return Type
(prefix?: string, override?: any, resetColours?: boolean) => any

[↑ Back to progressBarTools ↑]

waiters

[↑ Back to top ↑]

nextTick

nextTick(): Promise<unknown>
waiters.nextTick(): Promise<unknown>

Wait for the next tick

wait nextTick();
Return Type
Promise<unknown>

[↑ Back to waiters ↑]

keyListener

[↑ Back to top ↑]

getKeyListener

getKeyListener(callback: (keyName: string, rawValue: string) => void, isStart: boolean, isDebugLog: boolean): KeyListener

Listens for key presses and returns the key name and raw value.

const kl = getKeyListener((keyName, rawValue) => {
  // do something with keyName and rawValue
});

kl.start();

// later...

kl.stop();
#Parameter NameRequiredTypeDefault
0callbackYes(keyName: string, rawValue: string) => void
1isStartNobooleantrue
2isDebugLogNobooleanfalse
Return Type
KeyListener

[↑ Back to keyListener ↑]

KeyListener

KeyListener;

Returned by getKeyListener

[↑ Back to keyListener ↑]

start
kl.start(): void

Start listening for key presses

Return Type
void

[↑ Back to keyListener ↑]

stop
kl.stop(): void

Stop listening for key presses

Return Type
void

[↑ Back to keyListener ↑]

FAQs

Package last updated on 03 Feb 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc