• Stars
    star
    428
  • Rank 98,108 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Create text-based columns suitable for console output. Supports cell wrapping.

columnify

Columnify Unit Tests NPM Version License

Create text-based columns suitable for console output from objects or arrays of objects.

Columns are automatically resized to fit the content of the largest cell. Each cell will be padded with spaces to fill the available space and ensure column contents are left-aligned.

Designed to handle sensible wrapping in npm search results.

npm search before & after integrating columnify:

npm-tidy-search

Installation

$ npm install columnify

Usage

var columnify = require('columnify')
var columns = columnify(data, options)
console.log(columns)

Examples

Columnify Objects

Objects are converted to a list of key/value pairs:

var data = {
  "[email protected]": 1,
  "[email protected]": 3,
  "[email protected]": 2,
  "[email protected]": 3
}

console.log(columnify(data))

Output:

Custom Column Names

var data = {
  "[email protected]": 1,
  "[email protected]": 3,
  "[email protected]": 2,
  "[email protected]": 3
}

console.log(columnify(data, {columns: ['MODULE', 'COUNT']}))

Output:

Columnify Arrays of Objects

Column headings are extracted from the keys in supplied objects.

var columnify = require('columnify')

var columns = columnify([{
  name: 'mod1',
  version: '0.0.1'
}, {
  name: 'module2',
  version: '0.2.0'
}])

console.log(columns)

Output:

NAME    VERSION
mod1    0.0.1  
module2 0.2.0  

Filtering & Ordering Columns

By default, all properties are converted into columns, whether or not they exist on every object or not.

To explicitly specify which columns to include, and in which order, supply a "columns" or "include" array ("include" is just an alias).

var data = [{
  name: 'module1',
  description: 'some description',
  version: '0.0.1',
}, {
  name: 'module2',
  description: 'another description',
  version: '0.2.0',
}]

var columns = columnify(data, {
  columns: ['name', 'version']
})

console.log(columns)

Output:

NAME    VERSION
module1 0.0.1
module2 0.2.0

Global and Per Column Options

You can set a number of options at a global level (ie. for all columns) or on a per column basis.

Set options on a per column basis by using the config option to specify individual columns:

var columns = columnify(data, {
  optionName: optionValue,
  config: {
    columnName: {optionName: optionValue},
    columnName: {optionName: optionValue},
  }
})

Maximum and Minimum Column Widths

As with all options, you can define the maxWidth and minWidth globally, or for specified columns. By default, wrapping will happen at word boundaries. Empty cells or those which do not fill the minWidth will be padded with spaces.

var columns = columnify([{
  name: 'mod1',
  description: 'some description which happens to be far larger than the max',
  version: '0.0.1',
}, {
  name: 'module-two',
  description: 'another description larger than the max',
  version: '0.2.0',
}], {
  minWidth: 20,
  config: {
    description: {maxWidth: 30}
  }
})

console.log(columns)

Output:

NAME                 DESCRIPTION                    VERSION             
mod1                 some description which happens 0.0.1               
                     to be far larger than the max                      
module-two           another description larger     0.2.0               
                     than the max                         

Maximum Line Width

You can set a hard maximum line width using the maxLineWidth option. Beyond this value data is unceremoniously truncated with no truncation marker.

This can either be a number or 'auto' to set the value to the width of stdout.

Setting this value to 'auto' prevent TTY-imposed line-wrapping when lines exceed the screen width.

Truncating Column Cells Instead of Wrapping

You can disable wrapping and instead truncate content at the maximum column width by using the truncate option. Truncation respects word boundaries. A truncation marker, , will appear next to the last word in any truncated line.

var columns = columnify(data, {
  truncate: true,
  config: {
    description: {
      maxWidth: 20
    }
  }
})

console.log(columns)

Output:

NAME       DESCRIPTION          VERSION
mod1       some description…    0.0.1  
module-two another description… 0.2.0  

Align Right/Center

You can set the alignment of the column data by using the align option.

var data = {
  "[email protected]": 1,
  "[email protected]": 1,
  "[email protected]": 1
}

columnify(data, {config: {value: {align: 'right'}}})

Output:

align: 'center' works in a similar way.

Padding Character

Set a character to fill whitespace within columns with the paddingChr option.

var data = {
  "shortKey": "veryVeryVeryVeryVeryLongVal",
  "veryVeryVeryVeryVeryLongKey": "shortVal"
}

columnify(data, { paddingChr: '.'})

Output:

KEY........................ VALUE......................
shortKey................... veryVeryVeryVeryVeryLongVal
veryVeryVeryVeryVeryLongKey shortVal...................

Preserve Existing Newlines

By default, columnify sanitises text by replacing any occurance of 1 or more whitespace characters with a single space.

columnify can be configured to respect existing new line characters using the preserveNewLines option. Note this will still collapse all other whitespace.

var data = [{
  name: "[email protected]",
  paths: [
    "node_modules/tap/node_modules/glob",
    "node_modules/tape/node_modules/glob"
  ].join('\n')
}, {
  name: "[email protected]",
  paths: [
    "node_modules/tap/node_modules/nopt"
  ]
}, {
  name: "[email protected]",
  paths: "node_modules/tap/node_modules/runforcover"
}]

console.log(columnify(data, {preserveNewLines: true}))

Output:

NAME              PATHS
[email protected]        node_modules/tap/node_modules/glob
                  node_modules/tape/node_modules/glob
[email protected]        node_modules/tap/node_modules/nopt
[email protected] node_modules/tap/node_modules/runforcover

Compare this with output without preserveNewLines:

console.log(columnify(data, {preserveNewLines: false}))
// or just
console.log(columnify(data))
NAME              PATHS
[email protected]        node_modules/tap/node_modules/glob node_modules/tape/node_modules/glob
[email protected]        node_modules/tap/node_modules/nopt
[email protected] node_modules/tap/node_modules/runforcover

Custom Truncation Marker

You can change the truncation marker to something other than the default by using the truncateMarker option.

var columns = columnify(data, {
  truncate: true,
  truncateMarker: '>',
  widths: {
    description: {
      maxWidth: 20
    }
  }
})

console.log(columns)

Output:

NAME       DESCRIPTION          VERSION
mod1       some description>    0.0.1  
module-two another description> 0.2.0  

Custom Column Splitter

If your columns need some bling, you can split columns with custom characters by using the columnSplitter option.

var columns = columnify(data, {
  columnSplitter: ' | '
})

console.log(columns)

Output:

NAME       | DESCRIPTION                                                  | VERSION
mod1       | some description which happens to be far larger than the max | 0.0.1
module-two | another description larger than the max                      | 0.2.0

Control Header Display

Control whether column headers are displayed by using the showHeaders option.

var columns = columnify(data, {
  showHeaders: false
})

This also works well for hiding a single column header, like an id column:

var columns = columnify(data, {
  config: {
    id: { showHeaders: false }
  }
})

Transforming Column Data and Headers

If you need to modify the presentation of column content or heading content there are two useful options for doing that: dataTransform and headingTransform. Both of these take a function and need to return a valid string.

var columns = columnify([{
    name: 'mod1',
    description: 'SOME DESCRIPTION TEXT.'
}, {
    name: 'module-two',
    description: 'SOME SLIGHTLY LONGER DESCRIPTION TEXT.'
}], {
    dataTransform: function(data) {
        return data.toLowerCase()
    },
    headingTransform: function(heading) {
        return heading.toLowerCase()
    },
    config: {
        name: {
            headingTransform: function(heading) {
              heading = "module " + heading
              return "*" +  heading.toUpperCase() + "*"
            }
        }
    }
})

Output:

*MODULE NAME* description                           
mod1          some description text.                
module-two    some slightly longer description text.

Multibyte Character Support

columnify uses mycoboco/wcwidth.js to calculate length of multibyte characters:

var data = [{
  name: 'module-one',
  description: 'some description',
  version: '0.0.1',
}, {
  name: '这是一个很长的名字的模块',
  description: '这真的是一个描述的内容这个描述很长',
  version: "0.3.3"
}]

console.log(columnify(data))

Without multibyte handling:

i.e. before columnify added this feature

NAME         DESCRIPTION       VERSION
module-one   some description  0.0.1
这是一个很长的名字的模块 这真的是一个描述的内容这个描述很长 0.3.3

With multibyte handling:

NAME                     DESCRIPTION                        VERSION
module-one               some description                   0.0.1
这是一个很长的名字的模块 这真的是一个描述的内容这个描述很长 0.3.3

Contributions

 project  : columnify
 repo age : 8 years
 active   : 47 days
 commits  : 180
 files    : 57
 authors  :
   123	Tim Oxley           68.3%
    11	Nicholas Hoffman    6.1%
     8	Tim                 4.4%
     7	Arjun Mehta         3.9%
     6	Dany                3.3%
     5	Tim Kevin Oxley     2.8%
     5	Wei Gao             2.8%
     4	Matias Singers      2.2%
     3	Michael Kriese      1.7%
     2	sreekanth370        1.1%
     2	Dany Shaanan        1.1%
     1	Tim Malone          0.6%
     1	Seth Miller         0.6%
     1	andyfusniak         0.6%
     1	Isaac Z. Schlueter  0.6%

License

MIT

More Repositories

1

functional-javascript-workshop

A functional javascript workshop. No libraries required (i.e. no underscore), just ES5.
JavaScript
2,049
star
2

best-practices

Tidbits of developer best practices from around the web
1,275
star
3

keycode

Convert between keyboard keycodes and keynames and vice versa.
JavaScript
452
star
4

linklocal

Install local dependencies as symlinks.
JavaScript
349
star
5

npm-run

Run locally-installed node module executables.
JavaScript
183
star
6

polyfill-webcomponents

(deprecated) Browserify-compatible web-component polyfills, courtesy of Polymer
JavaScript
119
star
7

pkgfiles

Sanity check which files you are and aren't about to publish to npm
JavaScript
82
star
8

npm-which

Locate a program or locally installed node module's executable
JavaScript
78
star
9

offset

Get offset of an element within the document
JavaScript
59
star
10

wcwidth

Port of C's wcwidth() and wcswidth()
JavaScript
53
star
11

npm-path

Get a PATH containing locally installed module executables.
JavaScript
49
star
12

colornames

Map color names to HEX color values
JavaScript
45
star
13

react

Emit change events whenever object changes. Compatible with component/reactive.
JavaScript
41
star
14

sift

Fast String Distance (SIFT) Algorithm
JavaScript
40
star
15

npm3

Use npm v3 alongside your currently installed npm.
JavaScript
34
star
16

pkgcount

Produce a report on number of duplicate packages in node_modules.
JavaScript
29
star
17

scroll-position

Fire events when scrolling over dom elements
JavaScript
28
star
18

next-tick

process.nextTick for browser
JavaScript
25
star
19

robotlegs-utilities-UndoableCommand

Undoable Command Classes for Robotlegs Framework
JavaScript
24
star
20

npm-tutor

npm tutor for nodeconf 2014
JavaScript
23
star
21

saltmine

Arbitrary computation on the GPU using WebGL.
JavaScript
22
star
22

mdm-tunnel

A tunnel for getting behind NATs
JavaScript
20
star
23

cruft

Delete cruft from npm packages
JavaScript
19
star
24

nim

Command-line tool for inspecting node library objects, function implementations and listing properties – with syntax highlighting.
JavaScript
19
star
25

adventure-map

Simple exercise loader & generators for substack/adventure.
JavaScript
19
star
26

tojson-loader

WebPack Loader. Generate JSON assets at build-time.
JavaScript
18
star
27

css-path

Get CSS path to an element.
JavaScript
18
star
28

chimes

`Array.prototype` iteration methods for any iterator.
JavaScript
18
star
29

to-factory

Convert ES6 classes into factory functions so they can be called with or without new.
JavaScript
18
star
30

graphs

An intuitive data structure for graphs, implemented using ES6 data structures.
JavaScript
17
star
31

canvas-noise

Generate noise on a canvas.
JavaScript
16
star
32

serializerr

Convert Errors & Objects into an easily-serialized vanilla Object.
JavaScript
15
star
33

osi-licenses-full

All OSI-approved licenses as markdown
JavaScript
15
star
34

split-object

Work with Objects using built-in functional Array methods.
JavaScript
14
star
35

assertf

assert with printf message formatting
JavaScript
14
star
36

pkgrep

Powerful CLI tool to find, filter & format package data in node_modules.
JavaScript
13
star
37

npm-next

Wraps the latest unstable version of npm with different name so you can test alongside stable npm.
JavaScript
12
star
38

pkill

Convenience wrapper around `pkill(1)`
JavaScript
12
star
39

async-compose

Compose multiple async functions together to operate on a result.
JavaScript
11
star
40

voxel-real-physics

"Real" physics for VoxelJS with CANNON.JS
JavaScript
11
star
41

node-webhooks

easily create webhooks
JavaScript
10
star
42

scriptloader

Absurdly simple on-demand script loader.
JavaScript
10
star
43

protochain

Get the prototype chain of an object or primitive as an Array.
JavaScript
9
star
44

get

Create functions for use with map, reduce, filter, etc. that get object properties without need for anonymous wrappers.
JavaScript
9
star
45

color-convert

Convert colors between RGB, HSL & HSV.
JavaScript
9
star
46

express-koans

WIP Express 3 Koans
JavaScript
9
star
47

til

Today I learned
8
star
48

file-uploader

Programmatic multipart file uploads
JavaScript
8
star
49

enode

Easily harness the power of DNode/Upnode
JavaScript
8
star
50

beforefn

Execute a function before a function.
JavaScript
8
star
51

afterfn

Invoke a function after a function.
JavaScript
7
star
52

neuquant

NeuQuant Neural-Net Quantization Algorithm
JavaScript
7
star
53

guardfn

Conditionally execute a function
JavaScript
7
star
54

voxel-merge

Merge voxel chunks into convex volumes.
JavaScript
7
star
55

to-array

Convert an array-like object into an Array.
JavaScript
7
star
56

installed

Read all the installed packages in a folder, and produce an Array of all the data.
JavaScript
7
star
57

pkgresolve

Resolve a dependency from within the context of another package.
JavaScript
6
star
58

stitchup

Command-line stitchjs. Easily package and minify Javascript & Coffeescript CommonJS modules. Individual modules can be imported in the browser via require()
CoffeeScript
6
star
59

midi-experiment

JavaScript
6
star
60

assert

assert module ported from Node.JS for use as a component in the browser.
JavaScript
6
star
61

xpath

XPath utilities extracted from Firebug.
JavaScript
6
star
62

grunt-ember

Collate Ember templates into a single file
JavaScript
6
star
63

candlelightproject

Android IPv6 Geo-Location Based Wireless Mesh Network
Java
6
star
64

opengl-es2-docset

Dash docset for OpenGL ES 2.0 (i.e. webgl)
HTML
5
star
65

element-collection

Provide enumerable methods (find/select/filter) to collections of DOM Elements
JavaScript
5
star
66

ordered-set

A performant ES6 Set subclass that defines custom iteration order.
JavaScript
5
star
67

fnfn

Add before/after/around/guard functions to an API.
JavaScript
5
star
68

statement

A State Machine. Under Construction.
JavaScript
5
star
69

element-selector

Use mouse to select elements on the screen
JavaScript
4
star
70

npm-fresh

Keep your npm cache fresh.
JavaScript
4
star
71

cellutron

My first attempt at a game. Top down 'shooter' style. Pure AS3. Uses box2d physics, TweenMax for tweening & Flint for some particles.
ActionScript
4
star
72

npm-prev

Wraps previous stable version of npm so you can run it alongside other npm versions
JavaScript
4
star
73

candlelight

Android Mesh Network
3
star
74

silk-app-examples

Gregfroese's Silk Example Components
PHP
3
star
75

pipe-graph

Generate graphs of your streams.
JavaScript
3
star
76

overshadow-listeners

Add an event listener before existing listeners.
JavaScript
3
star
77

signalfn

Simple signalling
JavaScript
3
star
78

es5-workshop

Introduction to ES5 methods.
JavaScript
3
star
79

slow-install

An npm package that's slow to install. Slowness is configurable.
JavaScript
2
star
80

get-descriptor

Prototype-aware Object.getOwnPropertyDescriptor
JavaScript
2
star
81

eventsource-stream

Stream events to the browser as server-sent events.
JavaScript
2
star
82

bin-path

Get paths to module executables
JavaScript
2
star
83

node-xmlrpc-multicall

system.multicall for node-xmlrpc
JavaScript
2
star
84

attribute-binding

Bind to incoming data via attributes on your custom elements.
JavaScript
2
star
85

component-server

Easily serve local components as dependencies.
JavaScript
2
star
86

statemachine

A State Machine. Under Construction.
JavaScript
2
star
87

xpath2css

Convert simple xpaths to CSS selectors.
JavaScript
2
star
88

namefn

Rename a function.
JavaScript
2
star
89

lzw

LZW Encoder
JavaScript
2
star
90

component-badge

Generate component badges. WIP
JavaScript
2
star
91

backbone-events

Backbone.Events API as a component
JavaScript
2
star
92

browserify-slides

SingaporeJS 17 Feb 2014
JavaScript
2
star
93

component-dashdoc

Generate a Dash docset for published components.
JavaScript
2
star
94

tapef

Tape API with Mocha's error output. A hack.
JavaScript
2
star
95

switchstream

switch between output streams. e.g. a filter that pipes valid & invalid data to different streams
JavaScript
2
star
96

dom-support

Component to test browser feature support.
JavaScript
2
star
97

pincushion

JavaScript
2
star
98

expressions

Grab bag of template binding expressions.
JavaScript
2
star
99

overlay

Generate overlays over DOM elements.
JavaScript
2
star
100

npm-home

Chrome Extension. Redirects to a package's github page from npm.org. Simulates original behaviour of `npm home`.
JavaScript
2
star