### Method Chaining Examples Source: https://console-table.netlify.app/docs/api/table-methods Examples demonstrating how to chain multiple methods for building tables dynamically. ```APIDOC ## Method Chaining Examples ### Complete Table Building ```javascript const table = new Table() .addColumn({ name: "id", alignment: "left", color: "cyan" }) .addColumn({ name: "name", alignment: "center", color: "yellow" }) .addColumn({ name: "age", alignment: "right", color: "green" }) .addRow({ id: 1, name: "John", age: 25 }, { color: "blue" }) .addRow({ id: 2, name: "Jane", age: 30 }, { color: "red" }) .addRow({ id: 3, name: "Bob", age: 35 }, { separator: true }) .addRow({ id: 4, name: "Alice", age: 28 }) .printTable(); ``` ### Dynamic Table Building ```javascript const table = new Table(); const columns = ["id", "name", "email", "role"]; columns.forEach(col => { table.addColumn({ name: col, alignment: col === "id" ? "left" : "center" }); }); async function buildUserTable() { const users = await fetchUsers(); users.forEach((user, index) => { const options = {}; if (user.role === "admin") { options.color = "red"; } else if (user.role === "manager") { options.color = "yellow"; } if ((index + 1) % 5 === 0) { options.separator = true; } table.addRow(user, options); }); table.printTable(); } ``` ``` -------------------------------- ### Install ctp using Homebrew Source: https://console-table.netlify.app/docs/doc-cli-brew Use this command to install the ctp CLI tool via Homebrew. Ensure Homebrew is installed on your system. ```bash brew install console-table-printer/homebrew-console-table/ctp ``` -------------------------------- ### Install console-table-printer Source: https://console-table.netlify.app/docs Commands to install the package using different package managers. ```bash npm install --save console-table-printer ``` ```bash yarn add console-table-printer ``` ```bash pnpm add console-table-printer ``` ```bash bun add console-table-printer ``` -------------------------------- ### TableStyle Usage Examples Source: https://console-table.netlify.app/docs/api/configuration Examples of using default and custom border styles. ```javascript // Default border style (will use built-in default style) const table = new Table(); // Custom border style const table = new Table({ style: { headerTop: { left: "┌", mid: "┬", right: "┐", other: "─" }, headerBottom: { left: "├", mid: "┼", right: "┤", other: "─" }, tableBottom: { left: "└", mid: "┴", right: "┘", other: "─" }, vertical: "│" } }); ``` -------------------------------- ### Color Usage Examples Source: https://console-table.netlify.app/docs/api/configuration Examples of using built-in and custom colors. ```javascript // Built-in colors { name: "status", color: "red" } { name: "name", color: "green" } { name: "warning", color: "yellow" } // Custom colors const table = new Table({ colorMap: { success: '\x1b[32m', error: '\x1b[31m', warning: '\x1b[33m', info: '\x1b[36m' } }); // Use custom colors { name: "status", color: "success" } { name: "error", color: "error" } ``` -------------------------------- ### Sort Function Examples Source: https://console-table.netlify.app/docs/api/configuration Examples of various sorting strategies. ```javascript // Sort by numeric value in ascending order sort: (row1, row2) => row1.age - row2.age // Sort by numeric value in descending order sort: (row1, row2) => row2.score - row1.score // Sort by string alphabetically sort: (row1, row2) => row1.name.localeCompare(row2.name) // Sort by multiple fields sort: (row1, row2) => { if (row1.department !== row2.department) { return row1.department.localeCompare(row2.department); } return row1.name.localeCompare(row2.name); } // Sort by date sort: (row1, row2) => new Date(row1.created) - new Date(row2.created) ``` -------------------------------- ### Complete Table configuration example Source: https://console-table.netlify.app/docs/api/core-functions Demonstrates advanced usage including computed columns, custom sorting, filtering, and color mapping. ```typescript import { Table } from 'console-table-printer'; // Create table with comprehensive configuration const table = new Table({ // Define columns with specific properties columns: [ { name: "id", title: "ID", alignment: "left", color: "cyan", maxLen: 10 }, { name: "name", title: "Full Name", alignment: "center", color: "yellow", minLen: 15 }, { name: "age", title: "Age", alignment: "right", color: "green" } ], // Default options for any columns added later defaultColumnOptions: { alignment: "center", color: "white" }, // Pre-populate with data rows: [ { id: 1, name: "John Doe", age: 25 }, { id: 2, name: "Jane Smith", age: 30 } ], // Table styling // Default style will be used (omit style property for default borders) title: "Employee Directory", // Sorting by age in descending order sort: (row1, row2) => row2.age - row1.age, // Filter to show only adults filter: (row) => row.age >= 18, // Computed columns computedColumns: [ { name: "status", function: (row) => row.age >= 25 ? "Senior" : "Junior" } ], // Custom colors colorMap: { custom_blue: '\x1b[34m', custom_green: '\x1b[32m' } }); // Add more data table.addRow({ id: 3, name: "Bob Wilson", age: 35 }); // Print the table table.printTable(); ``` -------------------------------- ### Alignment Usage Examples Source: https://console-table.netlify.app/docs/api/configuration Examples of applying alignment to column definitions. ```javascript // Left alignment (default) { name: "id", alignment: "left" } // Center alignment { name: "name", alignment: "center" } // Right alignment { name: "age", alignment: "right" } ``` -------------------------------- ### Complete Table Configuration Example Source: https://console-table.netlify.app/docs/api/configuration Demonstrates how to configure a table with columns, default column options, pre-populated rows, a title, sorting, filtering, computed columns, specific column visibility, and custom color mapping. ```javascript const table = new Table({ // Column definitions columns: [ { name: "id", alignment: "left", color: "cyan" }, { name: "name", alignment: "center", color: "yellow" }, { name: "age", alignment: "right", color: "green" } ], // Default options for any columns added later defaultColumnOptions: { alignment: "center", color: "white", maxLen: 20 }, // Pre-populate with data rows: [ { id: 1, name: "John", age: 25 }, { id: 2, name: "Jane", age: 30 } ], // Table styling (using default style) // style: customStyleObject, // Use custom style object if needed title: "Employee Directory", // Sorting by age in descending order sort: (row1, row2) => row2.age - row1.age, // Filter to show only adults filter: (row) => row.age >= 18, // Computed columns computedColumns: [ { name: "status", function: (row) => row.age >= 25 ? "Senior" : "Junior" } ], // Show only specific columns enabledColumns: ["id", "name", "age", "status"], // Custom colors colorMap: { custom_blue: '\x1b[34m', custom_green: '\x1b[32m' } }); ``` -------------------------------- ### Print a basic table Source: https://console-table.netlify.app/docs Example showing how to import the printTable function and display an array of objects as a table. ```javascript import { printTable } from 'console-table-printer'; //Create a table const testCases = [ { Type: "Wish", text: "I would like some gelb bananen bitte", value: 100 }, { Type: "Hope", text: "I hope batch update is working", value: 300 }, ]; //print printTable(testCases); ``` -------------------------------- ### Column Configuration Examples Source: https://console-table.netlify.app/docs/api/configuration Illustrates various ways to configure individual columns, from simple name definition to specifying alignment, color, length constraints, and custom titles. ```javascript // Simple column { name: "id" } ``` ```javascript // Column with alignment { name: "name", alignment: "center" } ``` ```javascript // Column with color { name: "status", color: "red" } ``` ```javascript // Column with length constraints { name: "description", maxLen: 20, minLen: 10 } ``` ```javascript // Column with custom title { name: "created_at", title: "Created Date", alignment: "right" } ``` ```javascript // Complete configuration { name: "salary", title: "Annual Salary ($)", alignment: "right", color: "green", maxLen: 15, minLen: 10 } ``` -------------------------------- ### Install table-printer-cli with npm Source: https://console-table.netlify.app/docs/doc-cli-install-quick-start Use this command to install the table-printer-cli globally on your system using npm. This makes the `ctp` command available in your terminal. ```bash npm install --global table-printer-cli ``` -------------------------------- ### Row Addition Examples Source: https://console-table.netlify.app/docs/api/configuration Shows how to add rows to a table, with options for specifying row color and adding a separator. ```javascript // Simple row table.addRow({ id: 1, name: "John" }); ``` ```javascript // Row with color table.addRow({ id: 1, name: "John" }, { color: "green" }); ``` ```javascript // Row with separator table.addRow({ id: 1, name: "John" }, { separator: true }); ``` ```javascript // Row with both options table.addRow( { id: 1, name: "John" }, { color: "red", separator: true } ); ``` -------------------------------- ### Table Instance Creation: Bonus Example with Default Options Source: https://console-table.netlify.app/docs/doc-table-instance-creation Creates a Table instance with defined columns and specifies default options for all columns, such as alignment, color, and length constraints. Rows can also be pre-defined. ```javascript new Table({ columns: [ { name: "product" }, // Will inherit all defaultColumnOptions { name: "quantity" }, // Will inherit all defaultColumnOptions { name: "price", alignment: "right" } // Will override the default alignment ], defaultColumnOptions: { alignment: "center", // Default center alignment for all columns color: "green", // Default green color for all columns maxLen: 20, // Default maximum length for all columns minLen: 10 // Default minimum length for all columns }, rows: [ { product: "Laptop", quantity: 5, price: 999.99 }, { product: "Mouse", quantity: 10, price: 24.99 }, { product: "Keyboard", quantity: 7, price: 59.99 } ] }); ``` -------------------------------- ### Filter Function Examples Source: https://console-table.netlify.app/docs/api/configuration Examples of various filtering strategies. ```javascript // Filter by numeric value filter: (row) => row.age >= 18 // Filter by string value filter: (row) => row.status === "active" // Filter by multiple conditions filter: (row) => row.age >= 18 && row.status === "active" // Filter by array inclusion filter: (row) => row.tags.includes("senior") // Filter by date range filter: (row) => { const date = new Date(row.created); const start = new Date("2024-01-01"); const end = new Date("2024-12-31"); return date >= start && date <= end; } // Complex filter with nested properties filter: (row) => { return row.address?.city === "New York" && row.metadata?.active === true; } ``` -------------------------------- ### Install table-printer-cli with Yarn Source: https://console-table.netlify.app/docs/doc-cli-install-quick-start Use this command to install the table-printer-cli globally on your system using Yarn. This makes the `ctp` command available in your terminal. ```bash yarn global add table-printer-cli ``` -------------------------------- ### Implement Custom Table Style Source: https://console-table.netlify.app/docs/api/configuration Example of applying a custom style object to a Table instance. ```javascript const customStyle = { headerTop: { left: "╔", mid: "╦", right: "╗", other: "═" }, headerBottom: { left: "╟", mid: "╬", right: "╢", other: "═" }, tableBottom: { left: "╚", mid: "╩", right: "╝", other: "═" }, vertical: "║" }; const table = new Table({ style: customStyle, columns: [ { name: "id", alignment: "left" }, { name: "name", alignment: "center" }, { name: "age", alignment: "right" } ] }); ``` -------------------------------- ### Computed Column Examples Source: https://console-table.netlify.app/docs/api/configuration Provides examples of computed columns, including simple string concatenation, using the row index, performing calculations based on all rows, and implementing conditional logic for grading. ```javascript // Simple computation { name: "full_name", function: (row) => `${row.first_name} ${row.last_name}` } ``` ```javascript // Using row index { name: "row_number", function: (row, index) => index + 1 } ``` ```javascript // Using all rows for comparison { name: "percentile", function: (row, index, array) => { const sorted = array.sort((a, b) => a.score - b.score); const position = sorted.findIndex(r => r.id === row.id); return Math.round((position / array.length) * 100); } } ``` ```javascript // Complex computation with conditional logic { name: "grade", function: (row) => { if (row.score >= 90) return "A"; if (row.score >= 80) return "B"; if (row.score >= 70) return "C"; if (row.score >= 60) return "D"; return "F"; } } ``` -------------------------------- ### Create and Print a Table with Title Source: https://console-table.netlify.app/docs/doc-title Use this snippet to create a table with a title, define columns, add rows, and print the table to the console. Ensure 'console-table-printer' is installed. ```javascript import { printTable, Table } from 'console-table-printer'; const p = new Table({ title: "Analysis Results", columns: [{ name: "red_amount" }, { name: "blue_amount" }], }); // add rows p.addRows([ { red_amount: 2, blue_amount: 3, }, { red_amount: 1, blue_amount: 1, }, { red_amount: 5, blue_amount: 6, }, ]); // print p.printTable(); ``` -------------------------------- ### Print Table from JSON String Source: https://console-table.netlify.app/docs/doc-cli-install-quick-start This example demonstrates how to print a simple table by providing a JSON string directly to the `ctp` command using the `-i` flag. Ensure your JSON is correctly formatted. ```bash ctp -i '[{ "id":3, "text":"like" }, {"id":4, "text":"tea"}]' ``` -------------------------------- ### Print Table from Stdin Source: https://console-table.netlify.app/docs/doc-cli-install-quick-start This example shows how to pipe JSON data to the `ctp` command using the `-s` flag for reading from stdin. This is useful for processing data from other commands or files. ```bash echo '[{ "id":3, "text":"like" }, {"id":4, "text":"tea"}]' | ctp -s ``` -------------------------------- ### Multi-Level Sorting by Department and Salary Source: https://console-table.netlify.app/docs/doc-sort-filter Implement multi-level sorting by providing a comparison function to the 'sort' option. This example first sorts by 'department' alphabetically, then by 'salary' in descending order. ```javascript import { Table } from 'console-table-printer'; const table = new Table({ columns: [ { name: "department", alignment: "left" }, { name: "name", alignment: "left" }, { name: "salary", alignment: "right" } ], sort: (row1, row2) => { // First sort by department const deptCompare = row1.department.localeCompare(row2.department); if (deptCompare !== 0) return deptCompare; // Then sort by salary (descending) return row2.salary - row1.salary; } }); table.addRows([ { department: "Engineering", name: "Alice", salary: 85000 }, { department: "Engineering", name: "Bob", salary: 90000 }, { department: "Marketing", name: "Charlie", salary: 70000 }, { department: "Marketing", name: "David", salary: 75000 }, { department: "Sales", name: "Eve", salary: 65000 } ]); table.printTable(); ``` -------------------------------- ### RowData Examples Source: https://console-table.netlify.app/docs/api/configuration Various formats for row data including simple, complex, and computed values. ```javascript // Simple row { id: 1, name: "John", age: 25 } // Complex row with nested data { id: 1, name: "John Doe", age: 25, address: { street: "123 Main St", city: "New York" }, tags: ["developer", "senior"], active: true } // Row with computed values { id: 1, name: "John", score: 85, timestamp: new Date(), metadata: { created: "2024-01-01", updated: "2024-01-15" } } ``` -------------------------------- ### Mix Column Addition Methods Source: https://console-table.netlify.app/docs/doc-add-columns Combine different column addition methods (`addColumn` and `addColumns`) to construct your table structure flexibly. This example demonstrates adding columns individually and in batches. Ensure the Table class is imported. ```javascript import { Table } from 'console-table-printer'; const p = new Table(); // Add first column individually p.addColumn({ name: "ProductId", alignment: "left", color: "cyan" }); // Add multiple columns at once p.addColumns([ { name: "Category", alignment: "center" }, { name: "Quantity", alignment: "right" } ]); // Add one more column p.addColumn({ name: "Total", alignment: "right", color: "green" }); // Add some data p.addRows([ { ProductId: "P100", Category: "Electronics", Quantity: 5, Total: 2499.95 }, { ProductId: "P101", Category: "Accessories", Quantity: 10, Total: 299.90 } ]); p.printTable(); ``` -------------------------------- ### Create and Print Table Instance Source: https://console-table.netlify.app/docs/doc-table-instance-creation Demonstrates creating a table instance, adding rows with colors, and printing the table to the console. Requires importing the Table class. ```javascript import { Table } from 'console-table-printer'; //Create a table const p = new Table(); //add rows with color p.addRow( { "LineNr.": 1, text: "red wine please", value: 10.212 }, { color: "red" } ); p.addRow( { "LineNr.": 2, text: "green gemuse please", value: 20.0 }, { color: "green" } ); p.addRows([ //adding multiple rows are possible { "LineNr.": 3, text: "gelb bananen bitte", value: 100 }, { "LineNr.": 4, text: "update is working", value: 300 }, ]); //print p.printTable(); ``` -------------------------------- ### Show ctp help information Source: https://console-table.netlify.app/docs/doc-cli-brew Run this command to display all available options and usage instructions for the ctp tool. ```bash ctp --help ``` -------------------------------- ### Table Instance Creation: Simplest Way Source: https://console-table.netlify.app/docs/doc-table-instance-creation Creates a new Table instance using the simplest constructor. No arguments are needed. ```javascript new Table(); ``` -------------------------------- ### Configuration Best Practices Source: https://console-table.netlify.app/docs/api/configuration Offers recommendations for optimizing the configuration and usage of the console-table-printer. ```APIDOC ## Configuration Best Practices 1. **Column Definition:** Define columns in the constructor for better performance. 2. **Default Options:** Use `defaultColumnOptions` for consistent styling across columns. 3. **Computed Columns:** Keep computation functions simple and efficient to avoid performance bottlenecks. 4. **Custom Colors:** Use descriptive names for custom colors to improve readability. 5. **Sorting/Filtering:** Apply filters before sorting for better performance when dealing with large datasets. 6. **Type Safety:** Utilize TypeScript interfaces for column definitions and data structures to enhance the development experience and prevent errors. ``` -------------------------------- ### Table Rendering Source: https://console-table.netlify.app/docs/api/table-methods Demonstrates how to render a table as a string, both with default and custom configurations. ```APIDOC ## `render(): string` ### Description Renders the table as a string without printing it. ### Method `render` ### Parameters None ### Returns `string` - The formatted table as a string ### Request Example ```javascript const table = new Table(); table.addRow({ id: 1, name: "John" }); const tableString = table.render(); console.log(tableString); ``` ### Advanced Usage Example ```javascript const table = new Table({ title: "User Report" }); table.addRows([ { id: 1, name: "John", age: 25 }, { id: 2, name: "Jane", age: 30 } ]); const report = table.render(); fs.writeFileSync('user-report.txt', report); console.error(report); ``` ``` -------------------------------- ### Table Instance Creation Source: https://console-table.netlify.app/docs/doc-table-instance-creation Methods for initializing a new Table instance, ranging from simple constructors to complex configurations with column options, sorting, and filtering. ```APIDOC ## Table Instance Creation ### Description Initialize a new table instance. Can be done with no arguments, a list of column names, or a configuration object. ### Methods - `new Table()`: Simplest initialization. - `new Table(columns)`: Initialize with an array of column names. - `new Table(config)`: Initialize with a configuration object containing columns, sort, filter, and defaultColumnOptions. ### Configuration Object - **columns** (array) - Optional - Array of column objects with properties: name, alignment, color. - **sort** (function) - Optional - Comparator function for row sorting. - **filter** (function) - Optional - Predicate function for row filtering. - **defaultColumnOptions** (object) - Optional - Default settings for all columns (alignment, color, maxLen, minLen). ``` -------------------------------- ### Sort Table Rows by Value (Descending) Source: https://console-table.netlify.app/docs/doc-sort-filter Use the 'sort' option to define a custom function for sorting rows. This example sorts by the 'value' column in descending order. ```javascript import { Table } from 'console-table-printer'; const p = new Table({ columns: [{ name: "index" }, { name: "text" }, { name: "value" }], sort: (row1, row2) => +row2.value - +row1.value, // desc sorting order of rows (optional), }); p.addRow({ index: 1, text: "red wine", value: 11 }, { color: "green" }); p.addRow({ index: 2, text: "green gemuse", value: 21 }); p.addRow({ index: 3, text: "gelb bananen", value: 10 }); p.addRow({ index: 3, text: "rosa hemd wie immer", value: 13 }); p.addRow({ index: 4, text: "some more shit", value: 20 }, { color: "cyan" }); p.printTable(); ``` -------------------------------- ### Configure Minimum Column Length with minLen Source: https://console-table.netlify.app/docs/doc-limit-line-width Illustrates how to set a minimum length for column content. If the content is shorter than the specified minimum, the column will be padded to meet the minimum length. ```APIDOC ## Configure Minimum Column Length with minLen ### Description You can also use minLen accordingly. ### Method N/A (Configuration option within Table constructor) ### Endpoint N/A ### Parameters #### Table Constructor Options - **columns** (array) - Required - An array of column configuration objects. - **name** (string) - Required - The internal name of the column. - **alignment** (string) - Optional - The text alignment for the column ('left', 'right', 'center'). - **color** (string) - Optional - The text color for the column. - **minLen** (number) - Optional - The minimum length of the column content. If shorter, the column will be padded. - **maxLen** (number) - Optional - The maximum length of the column content. If exceeded, the text will wrap. - **title** (string) - Optional - The header title for the column. ### Request Example ```javascript import { Table } from 'console-table-printer'; const p = new Table({ columns: [ { name: "Index", alignment: "left", color: "red", minLen: 15, title: "minLen15", }, { name: "right_align_text", alignment: "right", maxLen: 15, title: "maxLen15", }, { name: "green", alignment: "center", color: "green", minLen: 20, title: "minLen20", }, ], }); p.addRow( { Index: 2, right_align_text: "This row is blue", green: 10.212, }, { color: "blue" } ); p.addRow( { Index: 3, right_align_text: "I would like some red wine please", green: 10.212, }, { color: "red" } ); p.printTable(); ``` ### Response N/A (This is a client-side configuration and rendering example) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Filter Table Rows by Value Less Than 20 Source: https://console-table.netlify.app/docs/doc-sort-filter Use the 'filter' option to provide a function that determines which rows to display. This example keeps rows where the 'value' is less than 20. ```javascript import { Table } from 'console-table-printer'; const p = new Table({ columns: [{ name: "index" }, { name: "text" }, { name: "value" }], filter: (row) => +row.value < 20, // filter rows with value < 20 }); p.addRow({ index: 1, text: "red wine", value: 11 }, { color: "green" }); p.addRow({ index: 2, text: "green gemuse", value: 21 }); p.addRow({ index: 3, text: "gelb bananen", value: 10 }); p.addRow({ index: 3, text: "rosa hemd wie immer", value: 13 }); p.addRow({ index: 4, text: "some more shit", value: 20 }, { color: "cyan" }); p.printTable(); ``` -------------------------------- ### Use Row Dividers with Computed Values Source: https://console-table.netlify.app/docs/doc-row-divider Row dividers are effective for visually separating summary or computed data from detailed entries. This example shows a divider before the yearly total sales and profit. ```javascript import { Table } from 'console-table-printer'; const table = new Table(); // Sales data table.addRow({ quarter: "Q1", sales: 1000, profit: 200 }); table.addRow({ quarter: "Q2", sales: 1500, profit: 350 }); table.addRow({ quarter: "Q3", sales: 1200, profit: 280 }); table.addRow({ quarter: "Q4", sales: 2000, profit: 500 }, { separator: true }); // Yearly summary table.addRow({ quarter: "Total", sales: 5700, profit: 1330 }); table.printTable(); ``` -------------------------------- ### Table Instance Creation: With Column Names Source: https://console-table.netlify.app/docs/doc-table-instance-creation Creates a new Table instance specifying only the column names as an array of strings. ```javascript new Table(["column1", "column2", "column3"]); ``` -------------------------------- ### Table Instance Creation: Complex Way Source: https://console-table.netlify.app/docs/doc-table-instance-creation Creates a new Table instance with custom column configurations, including alignment and color. Optional sorting and filtering can also be provided. ```javascript new Table({ // Default style will be used (omit style property for default borders) columns: [ { name: "column1", alignment: "left", color: "red" }, //with alignment and color { name: "column2", alignment: "right" }, { name: "column3" }, ], sort: (row1, row2) => row2.column1 - row1.column1, // sorting order of rows (optional) filter: (row) => row.column1 < 3, // filtering rows (optional) }); ``` -------------------------------- ### Print a simple table with ctp Source: https://console-table.netlify.app/docs/doc-cli-brew Use the -i flag to provide JSON input for creating a simple table. The input must be valid JSON. ```bash ctp -i '[{ "id":3, "text":"like" }, {"id":4, "text":"tea"}]' ``` -------------------------------- ### Complex Filtering with Multiple Conditions Source: https://console-table.netlify.app/docs/doc-sort-filter Use the 'filter' option with a function that combines multiple conditions for complex row filtering. This example filters for adults (age >= 18) who are either in Engineering or have a high salary (>= 50000). ```javascript import { Table } from 'console-table-printer'; const table = new Table({ columns: [ { name: "id", alignment: "left" }, { name: "name", alignment: "left" }, { name: "age", alignment: "right" }, { name: "department", alignment: "left" }, { name: "salary", alignment: "right" } ], filter: (row) => { // Multiple conditions const isAdult = row.age >= 18; const isHighSalary = row.salary >= 50000; const isEngineering = row.department === "Engineering"; // Complex logic return isAdult && (isHighSalary || isEngineering); } }); table.addRows([ { id: 1, name: "Alice", age: 25, department: "Engineering", salary: 85000 }, { id: 2, name: "Bob", age: 17, department: "Marketing", salary: 45000 }, { id: 3, name: "Charlie", age: 30, department: "Sales", salary: 60000 }, { id: 4, name: "David", age: 22, department: "Engineering", salary: 40000 } ]); table.printTable(); ``` -------------------------------- ### Initialize Table instance Source: https://console-table.netlify.app/docs/api/core-functions Create a Table instance using different constructor overloads for varying levels of configuration. ```typescript const table = new Table(); ``` ```typescript const table = new Table(["id", "name", "age"]); ``` ```typescript const table = new Table({ columns: [ { name: "id", alignment: "left", color: "red" }, { name: "name", alignment: "center" }, { name: "age", alignment: "right", color: "green" } ], // Default style will be used (omit style property for default borders) title: "User Data", sort: (row1, row2) => row1.id - row2.id, filter: (row) => row.age >= 18 }); ``` -------------------------------- ### Console Table Printer CLI Usage Source: https://console-table.netlify.app/docs/doc-cli-install-quick-start This displays the available options for the `ctp` command, including how to provide input via a string (`-i`) or stdin (`-s`), and how to access help (`-h`). ```bash Usage: ctp [options] Options: -i, --input input string -s, --stdin read input from stdin -h, --help display help for command ``` -------------------------------- ### Print Table to Console Source: https://console-table.netlify.app/docs/api/table-methods Use `printTable` to render the table to the console. This method does not accept parameters and returns void. ```javascript const table = new Table(); table.addRow({ id: 1, name: "John" }); table.printTable(); ``` ```javascript const table = new Table({ columns: [ { name: "id", alignment: "left" }, { name: "name", alignment: "center" }, { name: "age", alignment: "right" } ] }); table.addRows([ { id: 1, name: "John", age: 25 }, { id: 2, name: "Jane", age: 30 }, { id: 3, name: "Bob", age: 35 } ]); table.printTable(); ``` -------------------------------- ### Output Methods Source: https://console-table.netlify.app/docs/api/table-methods Methods for printing the table directly to the console or rendering it as a string. ```APIDOC ## Output Methods ### `printTable(): void` Prints the formatted table directly to the console. ### `render(): string` Renders the table as a string. - **Returns:** `string` - The formatted table as a string. ``` -------------------------------- ### Format Currency Values Source: https://console-table.netlify.app/docs/doc-transform Shows how to format numeric values as currency strings using a transform function. ```javascript import { Table } from 'console-table-printer'; const p = new Table({ columns: [ { name: 'item', alignment: 'left' }, { name: 'price', alignment: 'right', transform: (value) => `$${Number(value).toFixed(2)}` }, ], }); p.addRows([ { item: 'Coffee', price: 3.5 }, { item: 'Sandwich', price: 7.99 }, { item: 'Water', price: 1 }, ]); p.printTable(); ``` -------------------------------- ### Advanced Table Rendering and Export Source: https://console-table.netlify.app/docs/api/table-methods Demonstrates configuring a table with a title and exporting the rendered string to a file or external service. ```javascript const table = new Table({ title: "User Report" // Default style will be used (omit style property for default borders) }); table.addRows([ { id: 1, name: "John", age: 25 }, { id: 2, name: "Jane", age: 30 } ]); // Get the formatted string const report = table.render(); // Save to file const fs = require('fs'); fs.writeFileSync('user-report.txt', report); // Send via email sendEmail('admin@company.com', 'User Report', report); // Log to different console console.error(report); ``` -------------------------------- ### Render Table as String Source: https://console-table.netlify.app/docs/doc-render-console Use the render method to capture the table output as a string instead of printing it directly to the console. ```javascript import { Table } from 'console-table-printer'; const p = new Table(); p.addRow({ index: 1, text: "red wine", value: 10.212 }, { color: "green" }); p.addRow({ index: 2, text: "green gemuse", value: 20.0 }); const tableStr = p.render(); // print it in any other console whereever you like console.log(tableStr); ``` -------------------------------- ### Complete Table Building via Method Chaining Source: https://console-table.netlify.app/docs/api/table-methods Constructs a table by chaining column and row definitions, ending with a printTable call. ```javascript const table = new Table() .addColumn({ name: "id", alignment: "left", color: "cyan" }) .addColumn({ name: "name", alignment: "center", color: "yellow" }) .addColumn({ name: "age", alignment: "right", color: "green" }) .addRow({ id: 1, name: "John", age: 25 }, { color: "blue" }) .addRow({ id: 2, name: "Jane", age: 30 }, { color: "red" }) .addRow({ id: 3, name: "Bob", age: 35 }, { separator: true }) .addRow({ id: 4, name: "Alice", age: 28 }) .printTable(); ``` -------------------------------- ### Table Constructor Source: https://console-table.netlify.app/docs/api/core-functions Creates a new Table instance with optional configuration for advanced table formatting and data handling. ```APIDOC ## new Table ### Description Creates a new Table instance with optional configuration. ### Parameters - **options** (TableOptions) - Optional - Optional configuration object ### Returns - **Table** - A new Table instance ``` -------------------------------- ### Add Multiple Columns to a Table Instance Source: https://console-table.netlify.app/docs/api/table-methods Use `addColumns` to add an array of column configurations to the table. Returns the Table instance for chaining. ```javascript const table = new Table(); table.addColumns([ { name: "id", alignment: "left", color: "cyan" }, { name: "name", alignment: "center", color: "yellow" }, { name: "age", alignment: "right", color: "green" } ]); ``` ```javascript const table = new Table(); table.addColumns([ // Simple column { name: "id" }, // Column with alignment { name: "name", alignment: "center" }, // Column with color { name: "status", color: "red" }, // Column with length constraints { name: "description", maxLen: 20, minLen: 10 }, // Column with custom title { name: "created_at", title: "Created Date", alignment: "right" } ]); ``` -------------------------------- ### Configuring Table Styles with TypeScript Types Source: https://console-table.netlify.app/docs/doc-typescript Demonstrates using the COLOR and ALIGNMENT types to define column properties within a Table instance. ```typescript import { COLOR, Table, ALIGNMENT } from "../index"; const red_color: COLOR = "red"; const green_color: COLOR = "green"; const left_alignment: ALIGNMENT = "left"; const center_alignment: ALIGNMENT = "center"; const p = new Table({ columns: [ { name: "red_left_align_index", alignment: "left", color: red_color, }, { name: "right_align_text", alignment: left_alignment }, { name: "green_value_center", alignment: center_alignment, color: green_color, }, ], }); ``` -------------------------------- ### Limit Column Width with maxLen Source: https://console-table.netlify.app/docs/doc-limit-line-width Demonstrates how to set a maximum length for column content, causing text to wrap to multiple lines if it exceeds the specified limit. ```APIDOC ## Limit Column Width with maxLen ### Description Limit the max Length of each column using this. By default all lines are printed in single line. But in case you want to put max width of column lines will be splitted into multiples. ### Method N/A (Configuration option within Table constructor) ### Endpoint N/A ### Parameters #### Table Constructor Options - **columns** (array) - Required - An array of column configuration objects. - **name** (string) - Required - The internal name of the column. - **alignment** (string) - Optional - The text alignment for the column ('left', 'right', 'center'). - **color** (string) - Optional - The text color for the column. - **maxLen** (number) - Optional - The maximum length of the column content. If exceeded, the text will wrap. - **title** (string) - Optional - The header title for the column. ### Request Example ```javascript import { Table } from 'console-table-printer'; const p = new Table({ columns: [ { name: "Index", alignment: "left", color: "red" }, { name: "right_align_text", alignment: "right", maxLen: 10, title: "maxLen10", }, { name: "green", alignment: "center", color: "green" }, ], }); p.addRow( { Index: 2, right_align_text: "This row is blue", green: 10.212, }, { color: "blue" } ); p.addRow( { Index: 3, right_align_text: "I would like some red wine please", green: 10.212, }, { color: "red" } ); p.printTable(); ``` ### Response N/A (This is a client-side configuration and rendering example) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Apply Basic String Transformation Source: https://console-table.netlify.app/docs/doc-transform Demonstrates using a transform function to convert cell values to uppercase during table rendering. ```javascript import { Table } from 'console-table-printer'; const p = new Table({ columns: [ { name: 'original', alignment: 'left' }, { name: 'uppercase', alignment: 'left', transform: (value) => String(value).toUpperCase() }, ], }); p.addRow({ original: 'hello', uppercase: 'hello' }); p.addRow({ original: 'world', uppercase: 'world' }); p.addRow({ original: 'test', uppercase: 'test' }); p.printTable(); ``` -------------------------------- ### Implement Ranking with Row Index Source: https://console-table.netlify.app/docs/doc-computed-function Use the row index to generate rankings and calculate percentages relative to the maximum value in the dataset. ```javascript import { Table } from 'console-table-printer'; const table = new Table({ columns: [ { name: "name", alignment: "left" }, { name: "score", alignment: "right" } ], computedColumns: [ { name: "rank", function: (row, index) => `#${index + 1}` }, { name: "percentage", function: (row, index, array) => { const maxScore = Math.max(...array.map(r => r.score)); return `${((row.score / maxScore) * 100).toFixed(1)}%`; } } ] }); table.addRows([ { name: "Alice", score: 85 }, { name: "Bob", score: 92 }, { name: "Charlie", score: 78 } ]); table.printTable(); ```