Edge Runtime Format
The @edge-runtime/format package receives any JavaScript primitive or Object as input, returning the beauty string representation as output.
It follows the formatter spec (opens in a new tab) and can be used as drop-in replacement for util.inspect (opens in a new tab).
Installation
npm install @edge-runtime/format
This package includes built-in TypeScript support.
Usage
First, call createFormat
method for initialize your formatter:
import { createFormat } from '@edge-runtime/format'
const format = createFormat()
After that, you can interact with your formatter:
const obj = { [Symbol.for('foo')]: 'bar' }
format(obj)
// => '{ [Symbol(foo)]: 'bar' }'
You can output multiple objects by listing them:
format('The PI number is', Math.PI, '(more or less)')
// => 'The PI number is 3.141592653589793 (more or less)'
The string substitutions (printf style) is supported, and can be combined:
format('The PI number is %i', Math.PI, '(rounded)')
// => 'The PI number is 3 (rounded)'
In case you need to hide implementation details or want to customize how something should be printed, you can use the customInspectSymbol
option for that:
const customInspectSymbol = Symbol.for('edge-runtime.inspect.custom')
class Password {
constructor(value) {
Object.defineProperty(this, 'password', {
value,
enumerable: false,
})
}
toString() {
return 'xxx'
}
[customInspectSymbol]() {
return {
password: `<${this.toString()}>`,
}
}
}
format(new Password('r0sebud'))
// => { password: '<xxx>' }
API
createFormat([options])
It returns a formatter method.
options
formatError?: (error: Error) => string
It customizes how errors should be printed.
The default behavior is error.toString()
.
customInspectSymbol?: symbol
It sets the symbol to be used for printing custom behavior.
The default value is edge-runtime.inspect.custom
.