Installations
npm install ascii-table3
Developer
AllMightySauron
Developer Guide
Module System
CommonJS
Min. Node Version
>=11.14.0
Typescript Support
Yes
Node Version
16.15.1
NPM Version
9.8.0
Statistics
27 Stars
62 Commits
3 Forks
2 Watching
1 Branches
3 Contributors
Updated on 26 Oct 2024
Languages
JavaScript (100%)
Total Downloads
Cumulative downloads
Total Downloads
585,472
Last day
-8.1%
1,408
Compared to previous day
Last week
8.9%
8,783
Compared to previous week
Last month
-2.2%
32,980
Compared to previous month
Last year
270.2%
441,716
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Dev Dependencies
5
Ascii Table 3
ascii-table3
is a pure ascii table renderer and beautifier, heavily inspired by the ascii-table
package created by Beau Sorensen. The original package lacked support for multiple table styles and that is what motivated me to create this new one.
Currently with over a dozen predefined table styles, the collection style keeps growing. I am pretty sure there is a style for everyone. If not, you can even design your own custom style and add it to the library!
This package now includes support for ANSI escape sequences so that rendered tables can output rich console content with colors by relying on packages like chalk.
Please direct any issues, suggestions or feature requests to the ascii-table3 github page.
Existing code for the original ascii-table
package should run fine with very few changes (see examples below).
Usage
Node.js
1var { AsciiTable3 } = require('ascii-table3');
Basic usage
Tables are created programmatically.
1var { AsciiTable3, AlignmentEnum } = require('ascii-table3'); 2 3// create table 4var table = 5 new AsciiTable3('Sample table') 6 .setHeading('Name', 'Age', 'Eye color') 7 .setAlign(3, AlignmentEnum.CENTER) 8 .addRowMatrix([ 9 ['John', 23, 'green'], 10 ['Mary', 16, 'brown'], 11 ['Rita', 47, 'blue'], 12 ['Peter', 8, 'brown'] 13 ]); 14 15console.log(table.toString());
+-------------------------+
| Sample table |
+-------+-----+-----------+
| Name | Age | Eye color |
+-------+-----+-----------+
| John | 23 | green |
| Mary | 16 | brown |
| Rita | 47 | blue |
| Peter | 8 | brown |
+-------+-----+-----------+
We can make simpler tables without a title or headings as well.
1var table = 2 new AsciiTable3() 3 .setAlignCenter(3) 4 .addRowMatrix([ 5 ['John', 23, 'green'], 6 ['Mary', 16, 'brown'], 7 ['Rita', 47, 'blue'], 8 ['Peter', 8, 'brown'] 9 ]); 10 11console.log(table.toString());
+-------+----+-------+
| John | 23 | green |
| Mary | 16 | brown |
| Rita | 47 | blue |
| Peter | 8 | brown |
+-------+----+-------+
Using styles
Tables may be rendered using different styles.
1var table = 2 new AsciiTable3('Sample table') 3 .setHeading('Name', 'Age', 'Eye color') 4 .setAlignCenter(3) 5 .addRowMatrix([ 6 ['John', 23, 'green'], 7 ['Mary', 16, 'brown'], 8 ['Rita', 47, 'blue'], 9 ['Peter', 8, 'brown'] 10 ]); 11 12// set compact style 13table.setStyle('compact'); 14console.log(table.toString());
-------------------------
Name Age Eye color
------- ----- -----------
John 23 green
Mary 16 brown
Rita 47 blue
Peter 8 brown
These styles range from simple to more elaborate.
1table.setStyle('unicode-single'); 2console.log(table.toString());
┌─────────────────────────┐
│ Sample table │
├───────┬─────┬───────────┤
│ Name │ Age │ Eye color │
├───────┼─────┼───────────┤
│ John │ 23 │ green │
│ Mary │ 16 │ brown │
│ Rita │ 47 │ blue │
│ Peter │ 8 │ brown │
└───────┴─────┴───────────┘
API
Constructor
AsciiTable3([title])
Creates new table object.
title
- table title (optional)
1var { AsciiTable3 } = require('ascii-table3'); 2 3var table = new AsciiTable3('Data');
Static Methods
AsciiTable3.isNumeric(val)
Returns wether a val
is numeric or not, irrespective of its type.
val
- value to check
1AsciiTable3.isNumeric('test') // false 2AsciiTable3.isNumeric(10) // true 3AsciiTable3.isNumeric(3.14) // true
AsciiTable3.align(direction, val, len, [pad])
Shortcut to one of the three following methods.
direction
- alignment direction (AlignmentEnum.LEFT
,AlignmentEnum.CENTER
,AlignmentEnum.RIGHT
,AlignmentEnum.AUTO
)val
- string to alignlen
- total length of created stringpad
- padding / fill char (optional, default' '
)
Example:
1AsciiTable3.align(AlignmentEnum.LEFT, 'hey', 7) // 'hey '
AsciiTable3.alignLeft(val, len, [pad])
val
- string to alignlen
- total length of created stringpad
- padding / fill char (optional, default' '
)
Example:
1AsciiTable3.alignLeft('hey', 7, '-') // 'hey----'
AsciiTable3.alignCenter(val, len, [pad])
val
- string to alignlen
- total length of created stringpad
- padding / fill char (optional, default' '
)
Example:
1AsciiTable3.alignCenter('hey', 7) // ' hey '
AsciiTable3.alignRight(val, len, [pad])
val
- string to alignlen
- total length of created stringpad
- padding / fill char (optional, default' '
)
Example:
1AsciiTable3.alignRight('hey', 7) // ' hey'
AsciiTable3.alignAuto(val, len, [pad])
Attempts to do intelligent alignment of provided val
, String
input will
be left aligned, Number
types will be right aligned.
val
- string to alignlen
- total length of created stringpad
- padding / fill char (optional, default' '
)
Example:
1AsciiTable3.alignAuto('hey', 7) // 'hey '
AsciiTable3.wordWrap(str, maxWidth)
Wraps a string into multiple lines of a limited width.
str
- string to wrapmaxWidth
- maximum width for the wrapped string
1AsciiTable3.wordWrap('dummy', 5) // dummy 2 3AsciiTable3.wordWrap('this is a test', 5) 4// this 5// is a 6// test 7 8AsciiTable3.wordWrap('this is a test', 3) 9// thi 10// s 11// is 12// a 13// tes 14// t
AsciiTable3.truncateString(str, len)
Truncates a string up to a maximum number of characters (if needed).
str
- string to truncatelen
- maximum string lenght
Example:
1AsciiTable3.truncateString('bananas', 6) // 'ban...' 2AsciiTable3.truncateString('apples', 10) // 'apples'
AsciiTable3.arrayFill(len, [val])
Create a new array at the given len, filled with the given value, mainly used internally.
len
- length of arrayval
- fill value (optional)
Example:
1AsciiTable3.arrayFill(4, 0) // [0, 0, 0, 0] 2AsciiTable3.arrayFill(2) // [undefined, undefined]
AsciiTable3.ArrayResize(arr, len, [val])
Increases existing array size up to the desired limit.
arr
- array to increase sizelen
- new array lengthval
- fill value (optional)
1var arr = [ 'a', 'b', 'c' ]; 2 3AsciiTable3.arrayResize(arr, 4); // [ 'a', 'b', 'c', undefined ]
Instance methods
Title
instance.setTitle(title)
Sets the table title.
title
- table title
Example:
1var table = new AsciiTable3('Old Title'); 2 3table.setTitle('New Title');
instance.getTitle()
Get the current title of the table.
Example:
1table.getTitle() // 'New Title'
instance.setTitleAlign(direction)
Sets up the desired table title alignment.
direction
- table alignment direction
Example:
1// center table title 2table.setTitleAlign(AlignmentEnum.CENTER);
instance.setTitleAlignLeft()
Alias to instance.setTitleAlign(AlignmentEnum.LEFT)
instance.setTitleAlignCenter()
Alias to instance.setTitleAlign(AlignmentEnum.CENTER)
instance.setTitleAlignRight()
Alias to instance.setTitleAlign(AlignmentEnum.RIGHT)
instance.getTitleAlign()
Gets the current title alignment type (between AlignmentEnum.LEFT
, AlignmentEnum.CENTER
and AlignmentEnum.RIGHT
).
Example:
1table.setTitleAlignLeft(); 2 3table.getTitleAlign() // AlignmentEnum.LEFT
Heading
instance.setHeading(heading, [...])
Set the column headings for the table, takes arguments the same way as addRow
.
heading
- heading array or arguments
Example:
1table.setHeading('ID', 'Key', 'Value'); 2 3// or: 4 5table.setHeading(['ID', 'Key', 'Value']);
instance.getHeading()
Get the column head for the table as an array.
Example:
1table.setHeading('Name', 'Age', 'Height'); 2 3table.getHeading() // [ 'Name', 'Age', 'Height' ]
instance.setHeadingAlign(direction)
direction
- direction for heading alignment.
Example:
1table.setHeadingAlign(AlignmentEnum.LEFT);
instance.setHeadingAlignLeft()
Alias to instance.setHeadingAlignLeft(AlignmentEnum.LEFT)
instance.setHeadingAlignCenter()
Alias to instance.setHeadingAlignLeft(AlignmentEnum.CENTER)
instance.setHeadingAlignRight()
Alias to instance.setHeadingAlignLeft(AlignmentEnum.RIGHT)
instance.getHeadingAlign()
Gets the current heading alignment type (between AlignmentEnum.LEFT
, AlignmentEnum.CENTER
and AlignmentEnum.RIGHT
).
Example:
1table.setHeadinglignLeft(); 2 3table.getHeadingAlign() // AlignmentEnum.LEFT
Data rows
instance.addRow(row, [...])
Rows can be added using a single array argument, or the arguments if multiple args are used when calling the method.
row
- array or arguments of column values
Example:
1var table = new AsciiTable3(); 2 3table 4 .addRow(1, 'Bob', 52) 5 .addRow([2, 'John', 34]); 6 7console.log(table.toString());
+---+------+----+
| 1 | Bob | 52 |
| 2 | John | 34 |
+---+------+----+
instance.addNonZeroRow(row, [...])
Adds new row to table, as long as at least one of the numeric cells' value is not 0 (zero).
row
- array or arguments of column values
Example:
1var table = new AsciiTable3(); 2 3table 4 .addRow(1, 'Bob', 52) 5 .addRow([2, 'John', 34]); 6 7console.log(table.toString());
+---+------+----+
| 1 | Bob | 52 |
| 2 | John | 34 |
+---+------+----+
If all numeric values are 0 (zero) the new row is not added.
1table.addNonZeroRow(0, 'Dummy', 0); // should not be added 2 3console.log(table.toString());
+---+------+----+
| 1 | Bob | 52 |
| 2 | John | 34 |
+---+------+----+
instance.addRowMatrix(rows)
Bulk addRow
operation.
rows
- multidimensional array of rows
Example:
1table.addRowMatrix([ 2 [2, 'John', 34] 3, [3, 'Jim', 83] 4]); 5 6console.log(table.toString());
+---+------+----+
| 2 | John | 34 |
| 3 | Jim | 83 |
+---+------+----+
instance.getRows()
Get the multidimension array of rows from the table.
Example:
1table.addRowMatrix([ 2 [2, 'John', 34] 3, [3, 'Jim', 83] 4]); 5 6console.log(table.getRows());
1[ 2 [2, 'John', 34] 3, [3, 'Jim', 83] 4]
Styles
instance.setStyle(name)
Sets the table border style for rendering. Examples are provided below. New border styles are expected to be added as time goes by.
name
- the style name
Currently available styles are:
- none - Borderless
Sample table
Name Age Eye color
John 23 green
Mary 16 brown
Rita 47 blue
Peter 8 brown
- compact - Compact
-------------------------
Sample table
-------------------------
Name Age Eye color
------- ----- -----------
John 23 green
Mary 16 brown
Rita 47 blue
Peter 8 brown
- `ramac - beautified 7-bit ASCII output ( the default style)
+-------------------------+
| Sample table |
+-------+-----+-----------+
| Name | Age | Eye color |
+-------+-----+-----------+
| John | 23 | green |
| Mary | 16 | brown |
| Rita | 47 | blue |
| Peter | 8 | brown |
+-------+-----+-----------+
- ascii-table - mimics the original
ascii-table
npm package table style
.-------------------------.
| Sample table |
|-------------------------|
| Name | Age | Eye color |
|-------------------------|
| John | 23 | green |
| Mary | 16 | brown |
| Rita | 47 | blue |
| Peter | 8 | brown |
.-------------------------.
- ascii-reStructuredText - reStructuredText grid style
+-------------------------+
| Sample table |
+-------+-----+-----------+
| Name | Age | Eye color |
+=======+=====+===========+
| John | 23 | green |
| Mary | 16 | brown |
| Rita | 47 | blue |
| Peter | 8 | brown |
+-------+-----+-----------+
- ascii-reStructuredText-simple - reStructuredText simple style
===========================
Sample table
======== ===== ============
Name Age Eye color
======== ===== ============
John 23 green
Mary 16 brown
Rita 47 blue
Peter 8 brown
======== ===== ============
- ascii-dots - Ascii dotted border
...........................
: Sample table :
:.........................:
: Name : Age : Eye color :
:.......:.....:...........:
: John : 23 : green :
: Mary : 16 : brown :
: Rita : 47 : blue :
: Peter : 8 : brown :
:.......:.....:...........:
- ascii-rounded - Ascii rounded-corner border
.-------------------------.
| Sample table |
:-------.-----.-----------:
| Name | Age | Eye color |
:-------+-----+-----------:
| John | 23 | green |
| Mary | 16 | brown |
| Rita | 47 | blue |
| Peter | 8 | brown |
'-------'-----'-----------'
- ascii-clean - Clean(er) ascii table (no left and right borders)
1------------------------- 2 Sample table 3-------|-----|----------- 4 Name | Age | Eye color 5-------|-----|----------- 6 John | 23 | green 7 Mary | 16 | brown 8 Rita | 47 | blue 9 Peter | 8 | brown 10-------|-----|-----------
- ascii-girder - Ascii girder-like border
1//===========================\\ 2|| Sample table || 3|]=======[]=====[]===========[| 4|| Name || Age || Eye color || 5|]=======[]=====[]===========[| 6|| John || 23 || green || 7|| Mary || 16 || brown || 8|| Rita || 47 || blue || 9|| Peter || 8 || brown || 10\\=======[]=====[]===========//
- unicode-single - Single line unicode chars border
┌─────────────────────────┐
│ Sample table │
├───────┬─────┬───────────┤
│ Name │ Age │ Eye color │
├───────┼─────┼───────────┤
│ John │ 23 │ green │
│ Mary │ 16 │ brown │
│ Rita │ 47 │ blue │
│ Peter │ 8 │ brown │
└───────┴─────┴───────────┘
- unicode-double- Double line unicode chars border
╔═════════════════════════╗
║ Sample table ║
╠═══════╦═════╦═══════════╣
║ Name ║ Age ║ Eye color ║
╠═══════╬═════╬═══════════╣
║ John ║ 23 ║ green ║
║ Mary ║ 16 ║ brown ║
║ Rita ║ 47 ║ blue ║
║ Peter ║ 8 ║ brown ║
╚═══════╩═════╩═══════════╝
- unicode-mix - Mixed single/double line unicode style (single internal border and double external border)
╔═════════════════════════╗
║ Sample table ║
╟═══════╤═════╤═══════════╢
║ Name │ Age │ Eye color ║
╟───────┼─────┼───────────╢
║ John │ 23 │ green ║
║ Mary │ 16 │ brown ║
║ Rita │ 47 │ blue ║
║ Peter │ 8 │ brown ║
╚═══════╧═════╧═══════════╝
- unicode-round - Single line unicode style with rounded edges
╭─────────────────────────╮
│ Sample table │
├───────┬─────┬───────────┤
│ Name │ Age │ Eye color │
├───────┼─────┼───────────┤
│ John │ 23 │ green │
│ Mary │ 16 │ brown │
│ Rita │ 47 │ blue │
│ Peter │ 8 │ brown │
╰───────┴─────┴───────────╯
- github-markdown - github markdown style
| Sample table |
| Name | Age | Eye color |
|-------|-----|-----------|
| John | 23 | green |
| Mary | 16 | brown |
| Rita | 47 | blue |
| Peter | 8 | brown |
- reddit-markdown - reddit markdown style
Sample table
Name | Age | Eye color
-------|-----|-----------
John | 23 | green
Mary | 16 | brown
Rita | 47 | blue
Peter | 8 | brown
instance.getStyle()
Retrieves the current border style set for the instance. Style is returned as an object.
Example:
1var style = table.getStyle(); 2 3console.log (style);
1{ 2 "name": "unicode-double", 3 "borders": { 4 "top": { 5 "left": "╔", 6 "center": "═", 7 "right": "╗", 8 "colSeparator": "╦" 9 }, 10 "middle": { 11 "left": "╠", 12 "center": "═", 13 "right": "╣", 14 "colSeparator": "╬" 15 }, 16 "bottom": { 17 "left": "╚", 18 "center": "═", 19 "right": "╝", 20 "colSeparator": "╩" 21 }, 22 "data" : { 23 "left": "║", 24 "center": " ", 25 "right": "║", 26 "colSeparator": "║" 27 } 28 } 29 }
instance.addStyle(style)
Adds a custom new style to the list of predefined table styles.
style
- style object to add
Example:
1var table = 2 new AsciiTable3('Sample table') 3 .setHeading('Name', 'Age', 'Eye color') 4 .setAlignCenter(3) 5 .addRowMatrix([ 6 ['John', 23, 'green'], 7 ['Mary', 16, 'brown'], 8 ['Rita', 47, 'blue'], 9 ['Peter', 8, 'brown'] 10 ]); 11 12const roundedStyle = { 13 name: "rounded", 14 borders: { 15 top: { 16 left: ".", center: "-", right: ".", colSeparator: "." 17 }, 18 middle: { 19 left: ":", center: "-", right: ":", colSeparator: "+" 20 }, 21 bottom: { 22 left: "'", center: "-", right: "'", colSeparator: "'" 23 }, 24 data : { 25 left: "|", center: " ", right: "|", colSeparator: "|" 26 } 27 } 28}; 29 30table.addStyle(roundedStyle); 31table.setStyle("rounded"); 32 33console.log(table.toString());
.--------------------------------.
| Sample table |
:----------.--------.------------:
| Name | Age | Eye color |
:----------+--------+------------:
| John | 23 | green |
| Mary | 16 | brown |
| Rita | 47 | blue |
| Peter | 8 | brown |
'----------'--------'------------'
instance.removeBorder()
Shortcut for instance.setStyle('none').
Example:
1var table = 2 new AsciiTable3('Sample table') 3 .setHeading('Name', 'Age', 'Eye color') 4 .setAlignCenter(3) 5 .addRowMatrix([ 6 ['John', 23, 'green'], 7 ['Mary', 16, 'brown'], 8 ['Rita', 47, 'blue'], 9 ['Peter', 8, 'brown'] 10 ]); 11 12 table.removeBorder(); 13 14 console.log(table);
Sample table
Name Age Eye color
John 23 green
Mary 16 brown
Rita 47 blue
Peter 8 brown
instance.setWidth(idx, width)
Sets a preset width for a given column to be used when rendering the table.
idx
- table column index (starts at 1)width
- column width
Example:
1var table = 2 new AsciiTable3('Sample table') 3 .setHeading('Name', 'Age', 'Eye color') 4 .setAlignCenter(3) 5 .addRowMatrix([ 6 ['John', 23, 'green'], 7 ['Mary', 16, 'brown'], 8 ['Rita', 47, 'blue'], 9 ['Peter', 8, 'brown'] 10 ]); 11 12// set the age column width to 5 characters 13table.setWidth(1, 10); 14 15console.log(table.toString());
+----------+-----+-----------+
| Name | Age | Eye color |
+----------+-----+-----------+
| John | 23 | green |
| Mary | 16 | brown |
| Rita | 47 | blue |
| Peter | 8 | brown |
+----------+-----+-----------+
instance.getWidth(idx)
Get the preset width for a given column when rendering.
idx
- table column to get width (starts at 1)
Example:
1table.setWidth(2, 5); 2 3table.getWidth(2) // 5 4table.getWidth(1) // undefined (not set)
instance.setWidths(widths)
Sets column widths for table rendering using an array.
widths
- array of widths
Example:
1var table = 2 new AsciiTable3('Sample table') 3 .setHeading('Name', 'Age', 'Eye color') 4 .addRowMatrix([ 5 ['John', 23, 'green'], 6 ['Mary', 16, 'brown'], 7 ['Rita', 47, 'blue'], 8 ['Peter', 8, 'brown'] 9 ]); 10 11// set the age column width to 5 characters 12table.setWidths([10, 8, 12]); 13 14console.log(table.toString());
+----------+--------+------------+
| Name | Age | Eye color |
+----------+--------+------------+
| John | 23 | green |
| Mary | 16 | brown |
| Rita | 47 | blue |
| Peter | 8 | brown |
+----------+--------+------------+
instance.getWidths()
Gets the present widths for each column (if any).
Example:
1table.setWidths([1, undefined, 3]); 2 3table.getWidths() // [1, undefined, 3]
instance.setAlign(idx, direction)
idx
- column index to align (starts at 1)direction
- alignment direction, (AlignmentEnum.LEFT
,AlignmentEnum.CENTER
,AlignmentEnum.RIGHT
)
Example:
1table 2 .setAlign(2, AlignmentEnum.CENTER) 3 .setAlign(3, AlignmentEnum.RIGHT); 4 5console.log(table.toString());
+---+-----------+--------------------+
| a | apple | Some longer string |
| b | banana | hi |
| c | carrot | meow |
| e | elephants | |
+---+-----------+--------------------+
instance.setAlignLeft(idx)
Alias to instance.setAlign(idx, AlignmentEnum.LEFT)
instance.setAlignCenter(idx)
Alias to instance.setAlign(idx, AlignmentEnum.CENTER)
instance.setAlignRight(idx)
Alias to instance.setAlign(idx, AlignmentEnum.RIGHT)
instance.getAlign(idx)
Get column table alignment.
idx
- columns to get alignment (starts at 1)
Example:
1table.setAlignRight(2); 2 3table.getAlign(2) // AlignmentEnum.RIGHT
instance.setAligns(directions)
Set column alignment for all columns.
direction
- Array with alignment directions for each column (AlignmentEnum.LEFT
,AlignmentEnum.CENTER
,AlignmentEnum.RIGHT
).
Example:
1// for a 3 column table 2table.setAligns([AlignmentEnum.LEFT, AlignmentEnum.CENTER, AlignmentEnum.RIGHT]);
instance.getAligns()
Get array of column alignment for all table instance columns.
Example:
1// for a 3 column table 2table.setAligns([AlignmentEnum.LEFT, AlignmentEnum.CENTER, AlignmentEnum.RIGHT]); 3 4table.getAligns() // [AlignmentEnum.LEFT, AlignmentEnum.CENTER, AlignmentEnum.RIGHT]
instance.setWrapped(idx, [wrap])
Sets the wrapping property for a specific column (wrapped content will generate more than one data row if needed).
idx
- column to wrap (starts at 1).wrap
- wrap boolean setting (default is true).
1var table = 2 new AsciiTable3('Sample table') 3 .setHeading('Name', 'Age', 'Eye color') 4 .setAlignCenter(3) 5 .addRowMatrix([ 6 ['James Bond', 41, 'blue'], 7 ['Harry Potter', 18, 'brown'], 8 ['Scooby Doo', 23, 'brown'], 9 ['Mickey Mouse', 120, 'black'] 10 ]); 11 12// first column width is 8 characters and wrapped 13table.setWidth(1, 8).setWrapped(1); 14 15console.log(table.toString());
.------------------------------.
| Sample table |
:--------.--------.------------:
| Name | Age | Eye color |
:--------+--------+------------:
| James | 41 | blue |
| Bond | | |
| Harry | 18 | brown |
| Potter | | |
| Scooby | 23 | brown |
| Doo | | |
| Mickey | 120 | black |
| Mouse | | |
'--------'--------'------------'
instance.isWrapped(idx)
Gets the wrapping setting for a given column (true or false).
idx
- column to check (starts at 1)
1var table = 2 new AsciiTable3('Sample table') 3 .setHeading('Name', 'Age', 'Eye color') 4 .setAlignCenter(3) 5 .addRowMatrix([ 6 ['James Bond', 41, 'blue'], 7 ['Harry Potter', 18, 'brown'], 8 ['Scooby Doo', 23, 'brown'], 9 ['Mickey Mouse', 120, 'black'] 10 ]); 11 12// first column width is 8 characters and wrapped 13table.setWidth(1, 8).setWrapped(1); 14 15table.isWrapped(1) // true 16table.isWrapped(2) // false
instance.setWrappings(wrappings)
Sets the wrapping property for all columns (wrapped content will generate more than one data row if needed).
wrappings
- array of wrap boolean setting for each columns
Example:
1// for a 3 column table 2table.setWrappings([true, false, false]);
instance.getWrappings()
Gets the wrapping property for all columns .
Example:
1// for a 3 column table 2table.setWrappings([true, false, false]); 3 4table.getWrappings() // [true, false, false]
instance.setCellMargin(margin)
Sets internal margin for cell data (table default is 1).
margin
- number of empty characters to use for cell margin
Example 1 (no cell margin):
1var table = 2 new AsciiTable3('Sample table') 3 .setHeading('Name', 'Age', 'Eye color') 4 .setAlignCenter(3) 5 .addRowMatrix([ 6 ['John', 23, 'green'], 7 ['Mary', 16, 'brown'], 8 ['Rita', 47, 'blue'], 9 ['Peter', 8, 'brown'] 10 ]); 11 12table.setCellMargin(0);
+-------------------+
| Sample table |
+-----+---+---------+
|Name |Age|Eye color|
+-----+---+---------+
|John | 23| green |
|Mary | 16| brown |
|Rita | 47| blue |
|Peter| 8| brown |
+-----+---+---------+
Example 2 (cell margin set to 2):
1table.setCellMargin(2);
+-------------------------------+
| Sample table |
+---------+-------+-------------+
| Name | Age | Eye color |
+---------+-------+-------------+
| John | 23 | green |
| Mary | 16 | brown |
| Rita | 47 | blue |
| Peter | 8 | brown |
+---------+-------+-------------+
instance.getCellMargin()
Gets the current cell margin for the specified table instance.
Example:
1table.setCellMargin(2); 2 3table.getCellMargin() // 2
instance.setJustify([enabled])
Justify all columns to be the same width.
enabled
- Boolean for turning justify on or off (default is true).
1var table = new AsciiTable3('Dummy title') 2 .setHeading('Title', 'Count', 'Rate (%)') 3 .addRowMatrix([ 4 ['Dummy 1', 10, 2.3], 5 ['Dummy 2', 5, 3.1], 6 ['Dummy 3', 100, 3.14], 7 ['Dummy 4', 0, 1], 8 ]); 9 10table.setJustify(); 11 12console.log(table.toString());
+--------------------------------+
| Dummy title |
+----------+----------+----------+
| Title | Count | Rate (%) |
+----------+----------+----------+
| Dummy 1 | 10 | 2.3 |
| Dummy 2 | 5 | 3.1 |
| Dummy 3 | 100 | 3.14 |
| Dummy 4 | 0 | 1 |
+----------+----------+----------+
instance.getJustify()
Returns whether all table columns are to be rendered with the same width.
1table.setJustify(); 2 3table.getJustify() // true
Clearing data
instance.clear()
Clear / reset all table data
Example:
1table.clear();
instance.clearRows()
Resets all row data, maintaining title, headings, widths and style.
1table.clearRows();
Sorting
instance.sort(comparefunc)
Sort the table rows according to a specific criteria.
comparefunc
- compare function to run against the rows
Example:
1table.sort(function(a, b) { 2 return a[2] - b[2]; 3}); 4 5console.log(table.toString());
+---+------+----+
| 2 | John | 34 |
| 1 | Bob | 52 |
| 3 | Jim | 83 |
+---+------+----+
instance.sortColumn(index, [comparefunc])
Sorting shortcut for targeting a specific column.
index
- column idx to sortcomparefunc
- sorting compare function to run against column values (optional)
Example:
1// This is equivalent to the `sort` example above 2table.sortColumn(2);
instance.sortColumnDesc(index)
Descend sorting shortcut for targeting a specific column.
index
- column idx to sort
Example:
1table.sortColumnDesc(1); 2 3// This is equivalent to the `sort` example above 4console.log(table.toString());
+---+------+----+
| 1 | Bob | 52 |
| 2 | John | 34 |
| 3 | Jim | 83 |
+---+------+----+
Transposing
instance.transpose()
Transposes table by exchanging rows for columns.
Example:
1const table = 2 new AsciiTable3('Sample table') 3 .setHeading('Name', 'Age', 'Eye color') 4 .addRowMatrix([ 5 ['John', 23, 'green'], 6 ['Mary', 16, 'brown'], 7 ['Rita', 47, 'blue'], 8 ['Peter', 8, 'brown'] 9 ]); 10 11console.log(table.toString());
+-------------------------+
| Sample table |
+-------+-----+-----------+
| Name | Age | Eye color |
+-------+-----+-----------+
| John | 23 | green |
| Mary | 16 | brown |
| Rita | 47 | blue |
| Peter | 8 | brown |
+-------+-----+-----------+
1// transpose table 2table.transpose(); 3 4console.log(table.toString());
+------------------------------------------+
| Sample table |
+-----------+-------+-------+------+-------+
| Name | John | Mary | Rita | Peter |
| Age | 23 | 16 | 47 | 8 |
| Eye color | green | brown | blue | brown |
+-----------+-------+-------+------+-------+
Serialization
instance.toJSON()
Return the JSON representation of the table, this also allows us to call
JSON.stringify
on the instance.
Example:
1var table = new AsciiTable3('Title'); 2 3table 4 .setHeading('id', 'name') 5 .addRow(1, 'Bob') 6 .addRow(2, 'Steve') 7 .setWidths([3, 10]); 8 9console.log(table.toJSON());
1{ 2 "title": "Title", 3 "heading": ["id","name"], 4 "rows": [[1,"Bob"],[2,"Steve"]], 5 "formatting": { 6 "titleAlign": 2, 7 "headingAlign": 2, 8 "columns": { 9 "aligns": [3,3], 10 "widths": [3,10], 11 "wrappings": [false,false] 12 }, 13 "justify": false 14 } 15}
instance.fromJSON(obj)
Populate the table from JSON object, should match the toJSON
output above.
obj
- json object
Example:
1var table = new AsciiTable3() 2.fromJSON({ 3 "title": "Title", 4 "heading": ["id","name"], 5 "rows": [[1,"Bob"],[2,"Steve"]], 6 "formatting": { 7 "titleAlign": 2, 8 "headingAlign": 2, 9 "columns": { 10 "aligns": [3,3], 11 "widths": [3,10], 12 "wrappings": [false,false] 13 }, 14 "justify": false 15 } 16});
Rendering
instance.toString()
Renders the instance as a string for output.
Example:
1// create table 2var table = 3 new AsciiTable3('Sample table') 4 .setHeading('Name', 'Age', 'Eye color') 5 .setAlignCenter(3) 6 .addRowMatrix([ 7 ['John', 23, 'green'], 8 ['Mary', 16, 'brown'], 9 ['Rita', 47, 'blue'], 10 ['Peter', 8, 'brown'] 11 ]); 12 13console.log(table.toString());
+-------------------------+
| Sample table |
+-------+-----+-----------+
| Name | Age | Eye color |
+-------+-----+-----------+
| John | 23 | green |
| Mary | 16 | brown |
| Rita | 47 | blue |
| Peter | 8 | brown |
+-------+-----+-----------+
Install
With npm:
1npm install ascii-table3
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: Apache License 2.0: LICENSE:0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Info: jobLevel 'actions' permission set to 'read': .github/workflows/codeql-analysis.yml:28
- Info: jobLevel 'contents' permission set to 'read': .github/workflows/codeql-analysis.yml:29
- Warn: no topLevel permission defined: .github/workflows/codeql-analysis.yml:1
- Info: no jobLevel write permissions found
Reason
SAST tool detected but not run on all commits
Details
- Info: SAST configuration detected: CodeQL
- Warn: 0 commits out of 7 are checked with a SAST tool
Reason
Found 3/26 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:41: update your workflow using https://app.stepsecurity.io/secureworkflow/AllMightySauron/ascii-table3/codeql-analysis.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:45: update your workflow using https://app.stepsecurity.io/secureworkflow/AllMightySauron/ascii-table3/codeql-analysis.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:59: update your workflow using https://app.stepsecurity.io/secureworkflow/AllMightySauron/ascii-table3/codeql-analysis.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:72: update your workflow using https://app.stepsecurity.io/secureworkflow/AllMightySauron/ascii-table3/codeql-analysis.yml/main?enable=pin
- Info: 0 out of 4 GitHub-owned GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Score
5.3
/10
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More