1.0.4 • Published 6 years ago

formatr v1.0.4

Weekly downloads
2
License
ISC
Repository
github
Last release
6 years ago

Formatr

Simple utility for formatting string messages. If a single object is passed it is converted to string using node's util.inspect. When string format tokens are present e.g. %s, %d, %j and so on the string is formatted using node's util.format. For more advanced formatting you can use templating which allows piping values in order through custom transform handlers. Kind of similar to Angular's early pipes.

Install

$ npm install formatr

Usage

Import the module.

import * as formatr from 'formatr';
// OR
const formatr = require('formatr');

Format an object.

let result = formatr.format({ category: 'Movies', title: 'Office Space' });
// util.inspect converts object to string.
result = "{ category: 'Movies', title: 'Office Space' }"

Format using string format tokens.

let result = formatr.format('The movie %s was released in %d', 'Office Space', 1999);
// util.format maps args to tokens.
result = 'The movie Office Space was released in 1999'

Format using templating.

const obj = { name: 'Milton Waddams', stapler: 'Swingline' };
let result = formatr.format('My name is {{ name }} and I want my {{ stapler }} stapler.', obj);
// template formatter maps object values.
result = 'My name is Milton Waddams and I want my Swingline stapler.'

Format using templating and transforms.

// Add custom transform for quotes.
formatr.setOption('transforms.quote', (v) => `"${v}"`);
const obj = { name: 'milton waddams', stapler: 'swingline' };
let result = formatr.format('My name is {{ name|titlecase|quote }} and I want my {{ stapler|capitalize }} stapler.', obj);
// values are mapped from object name is titlecased and wrapped in quotes.
result = 'My name is "Milton Waddams" and I want my Swingline stapler.'

Options

Please refer to docs for more details but here are the basics.

Default

When using templating ONLY this is the default value when undefined is returned.

Colorize

This property is passed to util.inspect when formatting objects.

Hidden

This property is passed to util.inspect when formatting objects.

Depth

This property is passed to util.inspect when formatting objects.

Exp

When using template formatting this is the RegExp for parsing templates.

Strip

When using template formatting this is the RegExp for stripping parsed templates.

Split

When using template formatting this character used to split transforms.

Transform

When using template formatting this is a handler run on each value after getting from format object.

Transforms

When using template formatting this an object of built in transforms.

Docs

See https://blujedis.github.io/formatr/

Change

See CHANGE.md

License

See LICENSE.md

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago