1679111940
The tldr-pages project is a collection of community-maintained help pages for command-line tools, that aims to be a simpler, more approachable complement to traditional man pages.
Maybe you're new to the command-line world? Perhaps you're just a little rusty or can't always recall the arguments for commands like lsof
, or tar
?
It certainly doesn't help that the first option explained in man tar
is:
-b blocksize
Specify the block size, in 512-byte records, for tape drive I/O.
As a rule, this argument is only needed when reading from or writing to tape drives,
and usually not even then as the default block size of 20 records (10240 bytes) is very common.
There seems to be room for simpler help pages, focused on practical examples. How about:
This repository is just that: an ever-growing collection of examples for the most common UNIX, Linux, macOS, SunOS, Android and Windows command-line tools.
A popular and convenient way to access these pages on your computer is to install the Node.js client, which is supported by the tldr-pages project maintainers:
npm install -g tldr
Alternatively, you can also use the Python client, which can be installed via pip3
.
pip3 install tldr
Or Mac users can also install our C Client using Homebrew.
brew install tldr
Then you have direct access to simplified, easy-to-read help for commands, such as tar
, accessible through typing tldr tar
instead of the standard man tar
.
If you want an offline version without installing any software, check out the PDF version.
For browsing without installing a client to your computer, see the web client at https://tldr.inbrowser.app (with offline support using PWA).
There are also various other clients provided by the community, both for the command-line and for other platforms. For a comprehensive list of clients, head over to our Wiki.
All contributions are welcome!
Some ways to contribute include:
All tldr
pages are written in markdown, so they can be edited quite easily and changes can be submitted in pull requests here using Git on the command-line or using the GitHub web interface.
But we already have some plugins for different editors to enhance the tldr page editing experience:
For editors without a plugin system, we provide a set of configurations in a separate repo.
We strive to maintain a welcoming and collaborative community. If it's your first time contributing, have a look at the contributing guidelines, and go ahead!
If you'd like to contribute to translations, you can visit https://lukwebsforge.github.io/tldri18n/ to see the overall progress of all translations, and which translations are missing or outdated.
Command Line Interface Pages allows you to write standardized help pages for CLI, directories and configs.
Cheat allows you to create and view interactive cheatsheets on the command-line. It was designed to help remind *nix system administrators of options for commands that they use frequently, but not frequently enough to remember.
cheat.sh Aggregates cheat sheets from multiple sources (including tldr-pages) into 1 unified interface.
devhints Rico's cheatsheets are not just focused on the command-line and include a plethora of other cheatsheets related to programming.
eg provides detailed examples with explanations on the command-line. Examples come from the repository, but eg
supports displaying custom examples and commands alongside the defaults.
kb is a minimalist command-line knowledge base manager. kb can be used to organize your notes and cheatsheets in a minimalist and clean way. It also supports non-text files.
navi is an interactive cheatsheet tool, which allows you to browse through specific examples or complete commands on the fly.
bropages (deprecated) are a highly readable supplement to man pages. It shows concise, common-case examples for Unix commands. The examples are submitted by the user base, and can be voted up or down; the best entries are what people see first when they look up a command.
TL;DR stands for "Too Long; Didn't Read". It originated as Internet slang, where it is used to indicate that a long text (or parts of it) has been skipped as too lengthy. Read more in How-To Geek's article.
Author: tldr-pages
Source Code: https://github.com/tldr-pages/tldr
License: View license
1667488200
Coin tracking for hackers
cointop
is a fast and lightweight interactive terminal based UI application for tracking and monitoring cryptocurrency coin stats in real-time.
The interface is inspired by htop
and shortcut keys are inspired by vim
.
This connects to an instance of Cointop using SSH:
ssh cointop.sh
In action
See docs.cointop.sh/contributing
Many thanks to Simon Roberts, Alexis Hildebrandt, and all the contributors that made cointop better.
Cointop has been mentioned in:
Author: Cointop-sh
Source Code: https://github.com/cointop-sh/cointop
License: Apache-2.0 license
1667124660
Xterm.js is a front-end component written in TypeScript that lets applications bring fully-featured terminals to their users in the browser. It's used by popular projects such as VS Code, Hyper and Theia.
bash
, vim
, and tmux
, including support for curses-based apps and mouse events.bash
. Xterm.js can be connected to processes like bash
and let you interact with them (provide input, receive output).First, you need to install the module, we ship exclusively through npm, so you need that installed and then add xterm.js as a dependency by running:
npm install xterm
To start using xterm.js on your browser, add the xterm.js
and xterm.css
to the head of your HTML page. Then create a <div id="terminal"></div>
onto which xterm can attach itself. Finally, instantiate the Terminal
object and then call the open
function with the DOM object of the div
.
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="node_modules/xterm/css/xterm.css" />
<script src="node_modules/xterm/lib/xterm.js"></script>
</head>
<body>
<div id="terminal"></div>
<script>
var term = new Terminal();
term.open(document.getElementById('terminal'));
term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ')
</script>
</body>
</html>
The recommended way to load xterm.js is via the ES6 module syntax:
import { Terminal } from 'xterm';
⚠️ This section describes the new addon format introduced in v3.14.0, see here for the instructions on the old format
Addons are separate modules that extend the Terminal
by building on the xterm.js API. To use an addon, you first need to install it in your project:
npm i -S xterm-addon-web-links
Then import the addon, instantiate it and call Terminal.loadAddon
:
import { Terminal } from 'xterm';
import { WebLinksAddon } from 'xterm-addon-web-links';
const terminal = new Terminal();
// Load WebLinksAddon on terminal, this is all that's needed to get web links
// working in the terminal.
terminal.loadAddon(new WebLinksAddon());
The xterm.js team maintains the following addons, but anyone can build them:
xterm-addon-attach
: Attaches to a server running a process via a websocketxterm-addon-fit
: Fits the terminal to the containing elementxterm-addon-search
: Adds search functionalityxterm-addon-web-links
: Adds web link detection and interactionSince xterm.js is typically implemented as a developer tool, only modern browsers are supported officially. Specifically the latest versions of Chrome, Edge, Firefox, and Safari.
Xterm.js works seamlessly in Electron apps and may even work on earlier versions of the browsers. These are the versions we strive to keep working.
We also publish xterm-headless
which is a stripped down version of xterm.js that runs in Node.js. An example use case for this is to keep track of a terminal's state where the process is running and using the serialize addon so it can get all state restored upon reconnection.
The full API for xterm.js is contained within the TypeScript declaration file, use the branch/tag picker in GitHub (w
) to navigate to the correct version of the API.
Note that some APIs are marked experimental, these are added to enable experimentation with new ideas without committing to support it like a normal semver API. Note that these APIs can change radically between versions, so be sure to read release notes if you plan on using experimental APIs.
Xterm.js follows a monthly release cycle roughly.
All current and past releases are available on this repo's Releases page, you can view the high-level roadmap on the wiki and see what we're working on now by looking through Milestones.
Our CI releases beta builds to npm for every change that goes into master. Install the latest beta build with:
npm install -S xterm@beta
These should generally be stable, but some bugs may slip in. We recommend using the beta build primarily to test out new features and to verify bug fixes.
You can read the guide on the wiki to learn how to contribute and set up xterm.js for development.
Xterm.js is used in several world-class applications to provide great terminal experiences.
<ng-terminal></ng-terminal>
into your component.Do you use xterm.js in your application as well? Please open a Pull Request to include it here. We would love to have it on our list. Note: Please add any new contributions to the end of the list only.
Author: xtermjs
Source Code: https://github.com/xtermjs/xterm.js
License: MIT license
1666727400
A jekyll theme with inspiration from linux consoles for hackers, developers and script kiddies.
First, follow the steps in this Quickstart Guide if you're starting with Jekyll from scratch. Skip this if you already have an existing jekyll project.
You can also use the demo site's source code as template for an easy start.
Use this method for sites hosted with GitHub Pages only. To install:
Set remote_theme
in your project's Jekyll _config.yml
file:
remote_theme: b2a3e8/jekyll-theme-console
With Gem-based themes, directories such as the assets
, _layouts
, _includes
, and _sass
are stored in the theme’s gem, hidden from your immediate view. Yet all of the necessary directories will be read and processed during Jekyll’s build process.
This allows for easier installation and updating as you don't have to manage any of the theme files. To install:
Add this line to your Jekyll site's Gemfile
:
gem "jekyll-theme-console"
Fetch and update bundled gems by running the following Bundler command:
bundle
Set theme
in your project's Jekyll _config.yml
file:
theme: jekyll-theme-console
To update the theme run bundle update
.
In addition to jekyll's default configuration options, you can provide:
header_pages
to specify which pages should be displayed in navbarfooter
string, which will be inserted on the end of the page (doesn't support markup, but html)google_analytics
tracking id (tracking will be enabled only in production environments and only if you set this option, no Google Analytics code will be loaded if you don't set this option)listen_for_clients_preferred_style
boolean, used to allow users to choose light or dark style based on their preferences (mostly affected by OS dark or light theme, details see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)style
to specify which predefined style (colors) should be usedheader_pages:
- index.md
- about.md
style: dark # dark (default), light or hacker
listen_for_clients_preferred_style: true # false (default) or true
footer: 'follow us on <a href="https://twitter.com/xxx">twitter</a>'
google_analytics: UA-NNNNNNNN-N
Besides the predefined front matter variables from jekyll this theme also supports following variables:
title
to set a title for the pagelang
to specify the language, defaults to 'en'robots
to control the robot meta tag (details) - this may be useful for example to set NOINDEX
to tag pagesIf you want to customize this theme, follow this steps:
_layouts
directory for html-based changes_sass
and assets
for css-based changes_sass/base.scss
. You'll find style variables at the top._sass/_dark.scss
respectively in _sass/_light.scss
. You can change things like background-color there.Bug reports and pull requests are welcome on GitHub at https://github.com/b2a3e8/jekyll-theme-console. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
To set up your environment to develop this theme, run bundle install
.
Your theme is setup just like a normal Jekyll site! To test your theme, run bundle exec jekyll serve
and open your browser at http://localhost:4000
. This starts a Jekyll server using your theme. Add pages, documents, data, etc. like normal to test your theme's contents. As you make modifications to your theme and to your content, your site will regenerate and you should see the changes in the browser after a refresh, just like normal.
When your theme is released, only the files in _layouts
, _includes
, _sass
and assets
tracked with Git will be bundled. To add a custom directory to your theme-gem, please edit the regexp in jekyll-theme-console.gemspec
accordingly.
Author: b2a3e8
Source Code: https://github.com/b2a3e8/jekyll-theme-console
License: MIT license
1666180680
Collision was created by, and is maintained by Nuno Maduro, and is a package designed to give you beautiful error reporting when interacting with your app through the command line.
Requires PHP 8.1+
Require Collision using Composer:
composer require nunomaduro/collision --dev
Laravel | Collision |
---|---|
6.x | 3.x |
7.x | 4.x |
8.x | 5.x |
9.x | 6.x (PHPUnit 9.x or Pest v1.x) |
9.x | 7.x (PHPUnit 10.x or Pest v2.x) |
As an example, here is how to require Collision on Laravel 8.x:
composer require nunomaduro/collision:^5.0 --dev
Phpunit must be 9.0 or higher.
Add the Collision printerClass
to your phpunit.xml
in the phpunit
section:
<phpunit
printerClass="NunoMaduro\Collision\Adapters\Phpunit\Printer">
You need to register the handler in your code:
(new \NunoMaduro\Collision\Provider)->register();
Thank you for considering to contribute to Collision. All the contribution guidelines are mentioned here.
You can have a look at the CHANGELOG for constant updates & detailed information about the changes. You can also follow the twitter account for latest announcements or just come say hi!: @enunomaduro
Author: Nunomaduro
Source Code: https://github.com/nunomaduro/collision
License: MIT license
1665780960
PHP Insights was carefully crafted to simplify the analysis of your code directly from your terminal, and is the perfect starting point to analyze the code quality of your PHP projects. It was created by Nuno Maduro, logo design Caneco, and currently is maintained by Chris Gmyr, Jibé Barth, and Steve McDougall.
# First, install:
composer require nunomaduro/phpinsights --dev
# Then, use it:
./vendor/bin/phpinsights
# For Laravel:
First, publish the configuration file:
php artisan vendor:publish --provider="NunoMaduro\PhpInsights\Application\Adapters\Laravel\InsightsServiceProvider"
Then, use it:
php artisan insights
For full documentation, visit phpinsights.com.
Author: Nunomaduro
Source Code: https://github.com/nunomaduro/phpinsights
License: MIT license
1663151064
In today's post we will learn about 10 Popular Libraries for Advanced Console UIs in Go.
Console user interface may refer to: Command-line interface, user interface using only text. Text-based user interface, user interface with simple text-based menus and dialogues.
Table of contents:
Go package to make lightweight ASCII line graphs ╭┈╯.
go get github.com/guptarohit/asciigraph
package main
import (
"fmt"
"github.com/guptarohit/asciigraph"
)
func main() {
data := []float64{3, 4, 9, 6, 2, 4, 5, 8, 5, 10, 2, 7, 2, 5, 6}
graph := asciigraph.Plot(data)
fmt.Println(graph)
}
Running this example would render the following graph:
10.00 ┤ ╭╮
9.00 ┤ ╭╮ ││
8.00 ┤ ││ ╭╮││
7.00 ┤ ││ ││││╭╮
6.00 ┤ │╰╮ ││││││ ╭
5.00 ┤ │ │ ╭╯╰╯│││╭╯
4.00 ┤╭╯ │╭╯ ││││
3.00 ┼╯ ││ ││││
2.00 ┤ ╰╯ ╰╯╰╯
package main
import (
"fmt"
"github.com/guptarohit/asciigraph"
)
func main() {
data := [][]float64{{0, 1, 2, 3, 3, 3, 2, 0}, {5, 4, 2, 1, 4, 6, 6}}
graph := asciigraph.PlotMany(data)
fmt.Println(graph)
}
Running this example would render the following graph:
6.00 ┤ ╭─
5.00 ┼╮ │
4.00 ┤╰╮ ╭╯
3.00 ┤ │╭│─╮
2.00 ┤ ╰╮│ ╰╮
1.00 ┤╭╯╰╯ │
0.00 ┼╯ ╰
Ultimate ANSI colors for Golang. The package supports Printf/Sprintf etc.
Installation
Using gopkg.in.
go get -u gopkg.in/logrusorgru/aurora.v1
go get -u github.com/logrusorgru/aurora
Get
go get -u github.com/logrusorgru/aurora/v3
The v3 was introduced to support go.mod
and leave previous import paths as is. Currently, there is no changes between them (excluding the importpath's /v3 tail).
Test
go test -cover github.com/logrusorgru/aurora/v3
Replace the import path with your, if it's different.
Usage
package main
import (
"fmt"
. "github.com/logrusorgru/aurora"
)
func main() {
fmt.Println("Hello,", Magenta("Aurora"))
fmt.Println(Bold(Cyan("Cya!")))
}
Box CLI Maker is a Highly Customized Terminal Box Creator.
go get github.com/Delta456/box-cli-maker/v2
In main.go
package main
import "github.com/Delta456/box-cli-maker/v2"
func main() {
Box := box.New(box.Config{Px: 2, Py: 5, Type: "Single", Color: "Cyan"})
Box.Print("Box CLI Maker", "Highly Customized Terminal Box Maker")
}
box.New(config Config)
accepts a Config struct
with following parameters and returns a Box struct
.
Px
: Horizontal PaddingPy
: Vertical PaddingContentAlign
: Align the content inside the Box i.e. Center
, Left
and Right
Type
: Type of BoxTitlePos
: Position of the Title i.e. Inside
, Top
and Bottom
Color
: Color of the BoxBox struct
MethodsBox.Print(title, lines string)
prints Box from the specified arguments.
title
: Title of the Boxlines
: Content to be written inside the BoxBox.Println(title, lines string)
prints Box in a newline from the specified arguments.
title
: Title of the Boxlines
: Content to be written inside the BoxBox.String(title, lines string) string
return string
representation of Box.
title
: Title of the Boxlines
: Content to be written inside the BoxIt provides contextual formatting functions that have nearly identical usage of the fmt package. The ideas were borrowed from bootstrap's contextual color classes.
go get github.com/mingrammer/cfmt
package main
import (
"log"
"github.com/mingrammer/cfmt"
)
func main() {
cfmt.Success("User was created successfully")
cfmt.Infoln("Here are some candidates")
cfmt.Warningf("%s is not valid integer value\n", "123a")
log.Fatal(cfmt.Serrorf("Only numeric is allowed, got %s", "123.456a"))
}
cfmt is a small library for simple and convenient formatted stylized output to the console, providing an interface that is exactly the same as the standard fmt
and log
libraries.
go get -v github.com/i582/cfmt
To switch to cfmt
anywhere in the code, it is enough to add one letter c
to fmt
(or to log
), import the required part (cfmt
or clog
):
import (
"github.com/i582/cfmt/cmd/cfmt"
// or
"github.com/i582/cfmt/cmd/clog"
)
and you get all the possibilities, the library is fully compatible with the standard libraries fmt
and log
Let's take an example:
Suppose you need to display text and highlight some word or phrase. Using cfmt
, all that is needed is to wrap the desired part in {{}}
and after ::
write the desired styles:
cfmt.Println("This is a {{red color}}::red")
If we compare this with the gookit/color
library, then this example looks more complicated and less readable there:
fmt.Printf("This is a %s", color.Red.Sprintf("red color"))
Chalk is a go package for styling console/terminal output.
The api is pretty clean, there are default Colors and TextStyles which can be mixed to create more intense Styles. Styles and Colors can be printed in normal strings (i.e. fmt.Sprintf(chalk.Red)
), but Styles, Colors and TextStyles are more meant to be used to style specific text segments (i.e. fmt.Println(chalk.Red.Color("this is red")
) or fmt.Println(myStyle.Style("this is blue text that is underlined"))
).
Examples
There are a few examples in the examples directory if you want to see a very simplified version of what you can do with chalk.
The following code:
package main
import (
"fmt"
"github.com/ttacon/chalk"
)
func main() {
// You can just use colors
fmt.Println(chalk.Red, "Writing in colors", chalk.Cyan, "is so much fun", chalk.Reset)
fmt.Println(chalk.Magenta.Color("You can use colors to color specific phrases"))
// You can just use text styles
fmt.Println(chalk.Bold.TextStyle("We can have bold text"))
fmt.Println(chalk.Underline.TextStyle("We can have underlined text"))
fmt.Println(chalk.Bold, "But text styles don't work quite like colors :(")
// Or you can use styles
blueOnWhite := chalk.Blue.NewStyle().WithBackground(chalk.White)
fmt.Printf("%s%s%s\n", blueOnWhite, "And they also have backgrounds!", chalk.Reset)
fmt.Println(
blueOnWhite.Style("You can style strings the same way you can color them!"))
fmt.Println(
blueOnWhite.WithTextStyle(chalk.Bold).
Style("You can mix text styles with colors, too!"))
// You can also easily make styling functions thanks to go's functional side
lime := chalk.Green.NewStyle().
WithBackground(chalk.Black).
WithTextStyle(chalk.Bold).
Style
fmt.Println(lime("look at this cool lime text!"))
}
An ANSI colour terminal package for Go. Supports all ANSI colours and emphasis. Not compatible with Windows systems.
Project is no longer maintained.
This project is no longer maintained. However it's also complete. It has not and will not be updated with new Go features.
Installation
go get github.com/TreyBastian/colourize
Usage
package main
import (
c "github.com/TreyBastian/colourize"
"fmt"
)
func main() {
fmt.Println(c.Colourize("Hello World!", c.Green, c.Whitebg, c.Bold))
}
Dynamic configuration file templating tool for kubernetes manifest or general configuration files.
Download according to your computer architecture at release page go to release page
OS | Platform | Status |
---|---|---|
Ubuntu, Debian | amd64, arm64, 386 | available |
MacOS, Darwin | amd64, arm64, 386 | available |
Windows | amd64, arm64, 386 | available |
Extract using command like :
tar -xzf crab-cli-v0.1.0-darwin-amd64.tar.gz -C crab
Move to /usr/local/bin (Optional) :
cp crab/crab /usr/local/bin
Then check crab cli working properly :
make build
basic command fromat :
crab -f <fileinputpath> -r <keyvalue> -o <outputfilepath>
The non-invasive cross-platform terminal color library does not need to modify the Print method
package main
import (
"fmt"
"github.com/wzshiming/ctc"
)
func main() {
// No invasion
fmt.Println(ctc.BackgroundRed|ctc.ForegroundBlue, "Hello world", ctc.Reset)
}
Value | Description | Behavior |
---|---|---|
0 | Default | Returns all attributes to the default state prior to modification |
4 | Underline | Adds underline |
7 | Negative | Swaps foreground and background colors |
30~37 | Foreground | Applies non-bold/bright color to foreground |
40~47 | Background | Applies non-bold/bright color to background |
90~97 | Bright Foreground | Applies bold/bright color to foreground |
100~107 | Bright Background | Applies bold/bright color to background |
The goal of the project is to help render colored text in terminal applications with text attribute manipulation contained in text template. The idea is similar to HTML, e.g. <span style="color:green">Hello!</span>
ataman is not a full-featured template processor. It aims only on simple terminal text attribute, graphic mode in ANSI terms, manipulations using ANSI sequences.
To install the package use go get gopkg.in/workanator/go-ataman.v1
The next example shows basic usage of the package. The renderer here uses basic decoration style.
rndr := ataman.NewRenderer(ataman.BasicStyle())
tpl := "<light+green>%s<->, <bg+light+yellow,black,bold> <<%s>> <-><red>!"
fmt.Println(rndr.MustRenderf(tpl, "Hello", "Terminal World"))
This example produces colored text like this.
Renderer is able to pre-render templates so in further output operations they can be reused without parsing and rendering. In this example the renderer uses curly brackets decoration style.
rndr := ataman.NewRenderer(ataman.CurlyStyle())
prep := rndr.MustPrepare("{light_green}%s{-}, {bg_light_yellow+black+bold} <%s> {-}{red}!")
fmt.Println(rndr.MustRenderf(tpl, "Hi", "Everybody"))
The pre-rendered template implements fmt.Stringer
interface so it can be used in output operations without additional code, e.g.
prep := rndr.MustPrepare("{red}Red {green}Green {blue}Blue{-}")
fmt.Println(prep)
Thank you for following this article.
Golang UI Frameworks You MUST Learn 2022
1662416880
Inspect JavaScript object methods and properties in the console.
Provides colourful functions to inspect JavaScript objects.
probe()
function outputs a prototype hierarchy tree to the console.json()
function safely writes a stringified object output to the console.yaml()
function converts objects into yaml format and outputs to the console.ls()
function converts objects into a colourful format and outputs to the console.npm install --save-dev console-probe
Not recommended for production environments
const cp = require('./console-probe')
const arrLen = 2
const aussieSlang = {
'name': 'Aussie Slang Words',
'gday': Infinity,
'maccas': Number.NaN,
'arvo': undefined,
'straya': null,
'footy': {specky: true},
'biccy': (size, toppings) => {},
'servo': true,
'choccy': Symbol('Mmmmm...'),
'bottle-o': Error('Cheers mate! My shout next'),
'tinny': 42,
'coppa': new Date(),
'tradie': 'She\'ll be right mate?',
'postie': /a.long.regexp.that.keeps.giving/,
'garbo': [1, 2, 3],
'muso': new Int8Array(arrLen),
'cabbie': new Uint8Array(arrLen),
'ambo': new Uint8ClampedArray(arrLen),
'prezzie': new Int16Array(arrLen),
'chrissie': new Uint16Array(arrLen),
'cuppa': new Int32Array(arrLen),
'mate': new Uint32Array(arrLen),
'snag': new Float32Array(arrLen),
'drongo': new Float64Array(arrLen),
'fairDinkum': new Map([['foo', 'bar']]),
'bonza': new Set([['foo', 'bar']]),
'tooRight': new WeakMap(),
'dunny': new WeakSet(),
'cobber': new ArrayBuffer(arrLen),
'barbie': new SharedArrayBuffer(arrLen),
'stickybeak': Atomics,
'stoked': new DataView(new ArrayBuffer(arrLen)),
'ripper': Promise.resolve(),
'mongrel': (function * () {})(),
'holyDooley': function * (foo, bar) {},
'roo': async function (foo, bar) {}
}
const secret = Symbol('Hidden Property')
aussieSlang[secret] = 'Bogan'
// Calling console-probe functions.
cp.probe(aussieSlang) // Writes a prototype tree to the console
cp.json(aussieSlang) // Writes a JSON formatted object to the console
cp.yaml(aussieSlang) // Writes a YAML formatted object to the console
cp.ls(aussieSlang) // Writes a formatted object to the console
// Adding console-probe functions to the console.
console.probe(aussieSlang) // Throws exception 'console.probe is not a function'
console.json(aussieSlang) // Throws exception 'console.json is not a function'
console.yaml(aussieSlang) // Throws exception 'console.yaml is not a function'
console.ls(aussieSlang) // Throws exception 'console.ls is not a function'
cp.apply()
console.probe(aussieSlang) // Writes a prototype tree to the console
console.json(aussieSlang) // Writes a JSON formatted object to the console
console.yaml(aussieSlang) // Writes a YAML formatted object to the console
console.ls(aussieSlang) // Writes a formatted object to the console
// Adding console-probe functions to an object.
const foo = {}
cp.apply(foo)
foo.probe(aussieSlang) // Writes prototype tree to the console
foo.json(aussieSlang) // Writes a JSON formatted object to the console
foo.yaml(aussieSlang) // Writes a YAML formatted object to the console
foo.ls(aussieSlang) // Writes a formatted object to the console
The above code will produce the following results when it writes to the console.
probe
function output:Note: Type detection errors will display as [Unknown]
.
json
function output:yaml
function output:ls
function output:There are many amazing packages on npm
. Many of those packages are not well documented. Rather than go straight to reading source code I wrote console-probe
to inspect objects and discover methods and properties. Using Node.js with inspect is often a better approach however I don't always have it running; this is when console-probe
comes in handy.
The console-probe
package provides four functions that will write to the console:
probe(obj)
: The probe function uses Object.getOwnPropertyNames()
and Object.getOwnPropertySymbols()
to enumerate the members of an object through its prototype hierarchy. Using the type list from MDN the types are detected. After a little formatting the result is written to the console using the archy package with some colour added by chalk.json(obj, replacer, spacer, color)
: Uses fast-safe-stringify and json-colorizer to safely write the stringified object out to the console.yaml(obj, options, indentation)
: A simple wrapper around the prettyjson package render function.ls(obj)
: A simple wrapper around the jsome package render function.probe
FunctionDescription: Inspects the passed objects properties and methods, then the prototype of the passed object, and so on till the last prototype is analyzed. A tree of the properties and methods on each prototype is written to the console.
Method Signature: probe(object)
Parameter: object
can be any JavaScript type.
Details:
null
or undefined
will write [console-probe] Invalid Type:
to the console.Example:
const cp = require('console-probe')
cp.probe({ key: 'value' })
// Writes the object prototype hierarchy to the console
// See above for an example of the output
json
FunctionDescription: This function simply calls fast-safe-stringify and then adds color via json-colorizer. Once that is done it writes the result to the console.
Method Signature: json(object, replacer, spacer, color)
Parameter:
object
can be any object you wish to stringify.replacer
alters the behavior of the stringification process.spacer
inserts white space into the output JSON string for readability purposes.color
enables customization of the colour displayed.Details:
json
function defaults to replacer = null
and spacer = 2
.Example:
const cp = require('console-probe')
cp.json({ key: 'value' })
// Outputs the following to the console:
// {
// "key": "value"
// }
yaml
FunctionDescription: This function wraps the prettyjson render function and writes the result to the console. The result is a colorized formatted YAML representation of the object data.
Signature: yaml(object, options, indentation)
Parameter:
object
can be any object you wish to display in YAML format.options
should hold options for the prettyjson render function.indentation
controls the indentation for the YAML output.Details:
yaml
function is simply a wrapper around the prettyjson package.Example:
const cp = require('console-probe')
cp.yaml({ key: 'value' })
// Outputs the following to the console:
// key: value
ls
FunctionDescription: This function wraps the jsome render function and writes the result to the console. The result is a colorized formatted representation of the object data.
Signature: ls(object)
Parameter:
object
can be any object you wish to display.Details:
ls
function is simply a wrapper around the jsome package.Example:
const cp = require('console-probe')
cp.ls({ key: 'value' })
// Outputs the following to the console:
// {
// key: "value"
// }
apply
FunctionSignature: apply(object)
Parameter: object
can be any object you would like to add console-probe
functions to.
Details:
apply
function is a convenience method to add the console-probe
functions to an object.object
is passed to the apply
function then the console-probe
functions will be added to the console
object.console-probe
functions to the object.Example:
const cp = require('console-probe')
cp.apply()
// console now has a probe, json, yaml, and ls functions.
const foo = {}
cp.apply(foo)
// foo now has a probe, json, yaml, and ls functions.
Another approach to simply augment the console:
require('console-probe').apply()
// console.probe, console.json, console.yaml, and console.ls are now ready for use.
I, Grant Carthew, am a technologist, trainer, and Dad from Queensland, Australia. I work on code in a number of personal projects and when the need arises I build my own packages.
This project exists because I wanted to inspect objects from the console.
Everything I do in open source is done in my own time and as a contribution to the open source community.
If you are using my projects and would like to thank me or support me, please click the Patreon link below.
See my other projects on NPM.
git checkout -b my-new-feature
git commit -am 'Add some feature'
git push origin my-new-feature
ls
. Fixed README badges. Fixed null/undefined error.BigInt
type support. Updated dependencies.Author: Grantcarthew
Source Code: https://github.com/grantcarthew/node-console-probe
License: MIT license
1661338860
NOTE: As Chroma has just been released, its API is still in flux. That said, the high-level interface should not change significantly.
Chroma takes source code and other structured text and converts it into syntax highlighted HTML, ANSI-coloured text, etc.
Chroma is based heavily on Pygments, and includes translators for Pygments lexers and styles.
Prefix | Language |
---|---|
A | ABAP, ABNF, ActionScript, ActionScript 3, Ada, Angular2, ANTLR, ApacheConf, APL, AppleScript, Arduino, Awk |
B | Ballerina, Base Makefile, Bash, Batchfile, BibTeX, Bicep, BlitzBasic, BNF, Brainfuck |
C | C, C#, C++, Caddyfile, Caddyfile Directives, Cap'n Proto, Cassandra CQL, Ceylon, CFEngine3, cfstatement, ChaiScript, Chapel, Cheetah, Clojure, CMake, COBOL, CoffeeScript, Common Lisp, Coq, Crystal, CSS, Cython |
D | D, Dart, Diff, Django/Jinja, Docker, DTD, Dylan |
E | EBNF, Elixir, Elm, EmacsLisp, Erlang |
F | Factor, Fish, Forth, Fortran, FSharp |
G | GAS, GDScript, Genshi, Genshi HTML, Genshi Text, Gherkin, GLSL, Gnuplot, Go, Go HTML Template, Go Text Template, GraphQL, Groff, Groovy |
H | Handlebars, Haskell, Haxe, HCL, Hexdump, HLB, HTML, HTTP, Hy |
I | Idris, Igor, INI, Io |
J | J, Java, JavaScript, JSON, Julia, Jungle |
K | Kotlin |
L | Lighttpd configuration file, LLVM, Lua |
M | Mako, markdown, Mason, Mathematica, Matlab, MiniZinc, MLIR, Modula-2, MonkeyC, MorrowindScript, Myghty, MySQL |
N | NASM, Newspeak, Nginx configuration file, Nim, Nix |
O | Objective-C, OCaml, Octave, OnesEnterprise, OpenEdge ABL, OpenSCAD, Org Mode |
P | PacmanConf, Perl, PHP, PHTML, Pig, PkgConfig, PL/pgSQL, plaintext, Pony, PostgreSQL SQL dialect, PostScript, POVRay, PowerShell, Prolog, PromQL, Protocol Buffer, Puppet, Python 2, Python |
Q | QBasic |
R | R, Racket, Ragel, Raku, react, ReasonML, reg, reStructuredText, Rexx, Ruby, Rust |
S | SAS, Sass, Scala, Scheme, Scilab, SCSS, Smalltalk, Smarty, Snobol, Solidity, SPARQL, SQL, SquidConf, Standard ML, Stylus, Svelte, Swift, SYSTEMD, systemverilog |
T | TableGen, TASM, Tcl, Tcsh, Termcap, Terminfo, Terraform, TeX, Thrift, TOML, TradingView, Transact-SQL, Turing, Turtle, Twig, TypeScript, TypoScript, TypoScriptCssData, TypoScriptHtmlData |
V | VB.net, verilog, VHDL, VimL, vue |
W | WDTE |
X | XML, Xorg |
Y | YAML, YANG |
Z | Zig |
I will attempt to keep this section up to date, but an authoritative list can be displayed with chroma --list
.
Try out various languages and styles on the Chroma Playground.
Chroma, like Pygments, has the concepts of lexers, formatters and styles.
Lexers convert source text into a stream of tokens, styles specify how token types are mapped to colours, and formatters convert tokens and styles into formatted output.
A package exists for each of these, containing a global Registry
variable with all of the registered implementations. There are also helper functions for using the registry in each package, such as looking up lexers by name or matching filenames, etc.
In all cases, if a lexer, formatter or style can not be determined, nil
will be returned. In this situation you may want to default to the Fallback
value in each respective package, which provides sane defaults.
A convenience function exists that can be used to simply format some source text, without any effort:
err := quick.Highlight(os.Stdout, someSourceCode, "go", "html", "monokai")
To highlight code, you'll first have to identify what language the code is written in. There are three primary ways to do that:
Detect the language from its filename.
lexer := lexers.Match("foo.go")
Explicitly specify the language by its Chroma syntax ID (a full list is available from lexers.Names()
).
lexer := lexers.Get("go")
Detect the language from its content.
lexer := lexers.Analyse("package main\n\nfunc main()\n{\n}\n")
In all cases, nil
will be returned if the language can not be identified.
if lexer == nil {
lexer = lexers.Fallback
}
At this point, it should be noted that some lexers can be extremely chatty. To mitigate this, you can use the coalescing lexer to coalesce runs of identical token types into a single token:
lexer = chroma.Coalesce(lexer)
Once a language is identified you will need to pick a formatter and a style (theme).
style := styles.Get("swapoff")
if style == nil {
style = styles.Fallback
}
formatter := formatters.Get("html")
if formatter == nil {
formatter = formatters.Fallback
}
Then obtain an iterator over the tokens:
contents, err := ioutil.ReadAll(r)
iterator, err := lexer.Tokenise(nil, string(contents))
And finally, format the tokens from the iterator:
err := formatter.Format(w, style, iterator)
By default the html
registered formatter generates standalone HTML with embedded CSS. More flexibility is available through the formatters/html
package.
Firstly, the output generated by the formatter can be customised with the following constructor options:
Standalone()
- generate standalone HTML with embedded CSS.WithClasses()
- use classes rather than inlined style attributes.ClassPrefix(prefix)
- prefix each generated CSS class.TabWidth(width)
- Set the rendered tab width, in characters.WithLineNumbers()
- Render line numbers (style with LineNumbers
).LinkableLineNumbers()
- Make the line numbers linkable and be a link to themselves.HighlightLines(ranges)
- Highlight lines in these ranges (style with LineHighlight
).LineNumbersInTable()
- Use a table for formatting line numbers and code, rather than spans.If WithClasses()
is used, the corresponding CSS can be obtained from the formatter with:
formatter := html.New(html.WithClasses(true))
err := formatter.WriteCSS(w, style)
See the Pygments documentation for details on implementing lexers. Most concepts apply directly to Chroma, but see existing lexer implementations for real examples.
In many cases lexers can be automatically converted directly from Pygments by using the included Python 3 script pygments2chroma.py
. I use something like the following:
python3 _tools/pygments2chroma.py \
pygments.lexers.jvm.KotlinLexer \
> lexers/k/kotlin.go \
&& gofmt -s -w lexers/k/kotlin.go
See notes in pygments-lexers.txt for a list of lexers, and notes on some of the issues importing them.
Chroma supports HTML output, as well as terminal output in 8 colour, 256 colour, and true-colour.
A noop
formatter is included that outputs the token text only, and a tokens
formatter outputs raw tokens. The latter is useful for debugging lexers.
Chroma styles use the same syntax as Pygments.
All Pygments styles have been converted to Chroma using the _tools/style.py
script.
When you work with one of Chroma's styles, know that the chroma.Background
token type provides the default style for tokens. It does so by defining a foreground color and background color.
For example, this gives each token name not defined in the style a default color of #f8f8f8
and uses #000000
for the highlighted code block's background:
chroma.Background: "#f8f8f2 bg:#000000",
Also, token types in a style file are hierarchical. For instance, when CommentSpecial
is not defined, Chroma uses the token style from Comment
. So when several comment tokens use the same color, you'll only need to define Comment
and override the one that has a different color.
For a quick overview of the available styles and how they look, check out the Chroma Style Gallery.
A command-line interface to Chroma is included.
Binaries are available to install from the releases page.
The CLI can be used as a preprocessor to colorise output of less(1)
, see documentation for the LESSOPEN
environment variable.
The --fail
flag can be used to suppress output and return with exit status 1 to facilitate falling back to some other preprocessor in case chroma does not resolve a specific lexer to use for the given file. For example:
export LESSOPEN='| p() { chroma --fail "$1" || cat "$1"; }; p "%s"'
Replace cat
with your favourite fallback preprocessor.
When invoked as .lessfilter
, the --fail
flag is automatically turned on under the hood for easy integration with lesspipe shipping with Debian and derivatives; for that setup the chroma
executable can be just symlinked to ~/.lessfilter
.
Author: Alecthomas
Source Code: https://github.com/alecthomas/chroma
License: MIT license
1661013180
Hackable and configurable to the core, signale can be used for logging purposes, status reporting, as well as for handling the output rendering process of other node modules and applications.
Read this document in: 简体中文.
You can now support the development process through GitHub Sponsors.
Visit the contributing guidelines to learn more on how to translate this document into more languages.
Come over to Gitter or Twitter to share your thoughts on the project.
package.json
yarn add signale
npm install signale
Import signale and start using any of the default loggers.
View all of the available loggers.
await
complete
error
debug
fatal
fav
info
note
pause
pending
star
start
success
wait
warn
watch
log
const signale = require('signale');
signale.success('Operation successful');
signale.debug('Hello', 'from', 'L59');
signale.pending('Write release notes for %s', '1.2.0');
signale.fatal(new Error('Unable to acquire lock'));
signale.watch('Recursively watching build directory...');
signale.complete({prefix: '[task]', message: 'Fix issue #59', suffix: '(@klauscfhq)'});
To create a custom logger define an options
object yielding a types
field with the logger data and pass it as argument to a new signale instance.
const {Signale} = require('signale');
const options = {
disabled: false,
interactive: false,
logLevel: 'info',
scope: 'custom',
secrets: [],
stream: process.stdout,
types: {
remind: {
badge: '**',
color: 'yellow',
label: 'reminder',
logLevel: 'info'
},
santa: {
badge: '🎅',
color: 'red',
label: 'santa',
logLevel: 'info'
}
}
};
const custom = new Signale(options);
custom.remind('Improve documentation.');
custom.santa('Hoho! You have an unused variable on L45.');
Here is an example where we override the default error
and success
loggers.
const {Signale} = require('signale');
const options = {
types: {
error: {
badge: '!!',
label: 'fatal error'
},
success: {
badge: '++',
label: 'huge success'
}
}
};
const signale = new Signale();
signale.error('Default Error Log');
signale.success('Default Success Log');
const custom = new Signale(options);
custom.error('Custom Error Log');
custom.success('Custom Success Log');
The options
object can hold any of the following attributes: disabled
, interactive
, logLevel
, secrets
, stream
, scope
and types
.
disabled
Boolean
false
Disables the logging functionality of all loggers belonging to the created instance.
interactive
Boolean
false
Switches all loggers belonging to the created instance into the interactive mode.
logLevel
String
'info'
Sets the general logging level of the created instance. Can be one of the following:
'info'
- Displays all messages from all loggers.'timer'
- Displays messages only from the time
, timeEnd
, debug
, warn
, error
& fatal
loggers.'debug'
- Displays messages only from the debug
, warn
, error
& fatal
loggers.'warn'
- Displays messages only from the warn
, error
& fatal
loggers.'error'
- Displays messages only from the error
& fatal
loggers.secrets
(String|Number)[]
[]
An array holding secrets/sensitive-information to be removed from the body and metadata of to-be-logged messages and replaced with the default '[secure]'
string.
stream
stream.Writable|stream.Writable[]
process.stdout
Destination to which the data is written, can be a single valid Writable stream or an array holding multiple valid Writable streams.
scope
String|String[]
Name of the scope the logger is reporting from.
types
Object
Holds the configuration of the custom and default loggers.
Additionally, the configuration object of each custom/default logger type, defined in the types
option, can hold any of the following attributes: badge
, label
, color
, logLevel
& stream
.
badge
String
The icon corresponding to the logger.
label
String
The label used to identify the type of the logger.
color
String
The color of the label, can be any of the foreground colors supported by chalk.
logLevel
String
'info'
The log level corresponding to the logger. Messages originating from the logger are displayed only if the log level is greater or equal to the above described general logging level logLevel
of the Signale
instance.
stream
stream.Writable|stream.Writable[]
process.stdout
Destination to which the data is written, can be a single valid Writable stream or an array holding multiple valid Writable streams.
To create a scoped logger from scratch, define the scope
field inside the options
object and pass it as argument to a new signale instance.
const {Signale} = require('signale');
const options = {
scope: 'global scope'
};
const global = new Signale(options);
global.success('Successful Operation');
To create a scoped logger based on an already existing one, use the scope()
function, which will return a new signale instance, inheriting all custom loggers, timers, secrets, streams, configuration, log level, interactive mode & disabled statuses from the initial one.
const signale = require('signale');
const global = signale.scope('global scope');
global.success('Hello from the global scope');
function foo() {
const outer = global.scope('outer', 'scope');
outer.success('Hello from the outer scope');
setTimeout(() => {
const inner = outer.scope('inner', 'scope');
inner.success('Hello from the inner scope');
}, 500);
}
foo();
To initialize an interactive logger, create a new signale instance with the interactive
attribute set to true
. While into the interactive mode, previously logged messages originating from an interactive logger, will be overridden only by new ones originating from the same or a different interactive logger. Note that regular messages originating from regular loggers are not overridden by the interactive ones.
const {Signale} = require('signale');
const interactive = new Signale({interactive: true, scope: 'interactive'});
interactive.await('[%d/4] - Process A', 1);
setTimeout(() => {
interactive.success('[%d/4] - Process A', 2);
setTimeout(() => {
interactive.await('[%d/4] - Process B', 3);
setTimeout(() => {
interactive.error('[%d/4] - Process B', 4);
setTimeout(() => {}, 1000);
}, 1000);
}, 1000);
}, 1000);
By default, all signale instances log their messages to the process.stdout
stream. This can be modified, to match your own preference, through the stream
property, where you can define a single or multiple valid Writable streams, which will be used by all logger types to log your data. Additionally, it is possible to define one or more Writable streams exclusively for a specific logger type, thus write data independently from the rest logger types.
const {Signale} = require('signale');
const options = {
stream: process.stderr, // All loggers will now write to `process.stderr`
types: {
error: {
// Only `error` will write to both `process.stdout` & `process.stderr`
stream: [process.stdout, process.stderr]
}
}
};
const signale = new Signale(options);
signale.success('Message will appear on `process.stderr`');
signale.error('Message will appear on both `process.stdout` & `process.stderr`');
By utilizing the secrets
option, secrets and other sensitive information can be filtered out from the body as well as the metadata, i.e. scope names etc, of to-be-logged messages. The option is part of the configuration object passed to a Signale
instance on its initialization, and is of type Array<String|Number>
. The array can hold multiple secrets, all of which are removed, if present, from the to-be-logged messages and are replaced with the default '[secure]'
string. Additionally, when the unary signale.scope(name)
function is used, the returned Signale
instance inherits all the secrets belonging to its parent. The secrets checking process is performed in a case-sensitive manner. Also, the unary signale.addSecrets()
and the nullary signale.clearSecrets()
functions are available through the API for adding and clearing secrets respectively.
It is critical and highly recommended to not type directly secrets in your code, thus the following example serves only as a simple & easily reproducible usage demonstration.
const {Signale} = require('signale');
// In reality secrets could be securely fetched/decrypted through a dedicated API
const [USERNAME, TOKEN] = ['klaussinani', 'token'];
const logger1 = new Signale({
secrets: [USERNAME, TOKEN]
});
logger1.log('$ exporting USERNAME=%s', USERNAME);
logger1.log('$ exporting TOKEN=%s', TOKEN);
// `logger2` inherits all secrets from its parent `logger1`
const logger2 = logger1.scope('parent');
logger2.log('$ exporting USERNAME=%s', USERNAME);
logger2.log('$ exporting TOKEN=%s', TOKEN);
Timer are managed by the time()
and timeEnd()
functions. A unique label can be used to identify a timer on initialization, though if none is provided the timer will be assigned one automatically. In addition, calling the timeEnd()
function without a specified label will have as effect the termination of the most recently initialized timer, that was created without providing a label.
const signale = require('signale');
signale.time('test');
signale.time();
signale.time();
setTimeout(() => {
signale.timeEnd();
signale.timeEnd();
signale.timeEnd('test');
}, 500);
To enable global configuration define the options under the signale
namespace in your package.json
.
The following illustrates all the available options with their respective default values.
{
"signale": {
"displayScope": true,
"displayBadge": true,
"displayDate": false,
"displayFilename": false,
"displayLabel": true,
"displayTimestamp": false,
"underlineLabel": true,
"underlineMessage": false,
"underlinePrefix": false,
"underlineSuffix": false,
"uppercaseLabel": false
}
}
View all of the available options in detail.
To enable local configuration call the config()
function on your signale instance. Local configurations will always override any pre-existing configuration inherited from package.json
.
In the following example, loggers in the foo.js
file will run under their own configuration, overriding the package.json
one.
// foo.js
const signale = require('signale');
// Overrides any existing `package.json` config
signale.config({
displayFilename: true,
displayTimestamp: true,
displayDate: false
});
signale.success('Hello from the Global scope');
Also, scoped loggers can have their own independent configuration, overriding the one inherited by the parent instance or package.json
.
// foo.js
const signale = require('signale');
signale.config({
displayFilename: true,
displayTimestamp: true,
displayDate: false
});
signale.success('Hello from the Global scope');
function foo() {
// `fooLogger` inherits the config of `signale`
const fooLogger = signale.scope('foo scope');
// Overrides both `signale` and `package.json` configs
fooLogger.config({
displayFilename: true,
displayTimestamp: false,
displayDate: true
});
fooLogger.success('Hello from the Local scope');
}
foo();
<logger>(message[, message]|messageObj|errorObj)
logger
Function
Can be any default or custom logger.
message
String
Can be one or more comma delimited strings.
const signale = require('signale');
signale.success('Successful operation');
//=> ✔ success Successful operation
signale.success('Successful', 'operation');
//=> ✔ success Successful operation
signale.success('Successful %s', 'operation');
//=> ✔ success Successful operation
errorObj
Error Object
Can be any error object.
const signale = require('signale');
signale.error(new Error('Unsuccessful operation'));
//=> ✖ error Error: Unsuccessful operation
// at Module._compile (module.js:660:30)
// at Object.Module._extensions..js (module.js:671:10)
// ...
messageObj
Object
Can be an object holding the prefix
, message
and suffix
attributes, with prefix
and suffix
always prepended and appended respectively to the logged message
.
const signale = require('signale');
signale.complete({prefix: '[task]', message: 'Fix issue #59', suffix: '(@klaussinani)'});
//=> [task] ☒ complete Fix issue #59 (@klaussinani)
signale.complete({prefix: '[task]', message: ['Fix issue #%d', 59], suffix: '(@klaussinani)'});
//=> [task] ☒ complete Fix issue #59 (@klaussinani)
scope(name[, name])
Defines the scope name of the logger.
name
String
Can be one or more comma delimited strings.
const signale = require('signale');
const foo = signale.scope('foo');
const fooBar = signale.scope('foo', 'bar');
foo.success('foo');
//=> [foo] › ✔ success foo
fooBar.success('foo bar');
//=> [foo] [bar] › ✔ success foo bar
unscope()
Clears the scope name of the logger.
const signale = require('signale');
const foo = signale.scope('foo');
foo.success('foo');
//=> [foo] › ✔ success foo
foo.unscope();
foo.success('foo');
//=> ✔ success foo
config(settingsObj)
Sets the configuration of an instance overriding any existing global or local configuration.
settingsObj
Object
Can hold any of the documented options.
// foo.js
const signale = require('signale');
signale.config({
displayFilename: true,
displayTimestamp: true,
displayDate: true
});
signale.success('Successful operations');
//=> [2018-5-15] [11:12:38] [foo.js] › ✔ success Successful operations
time([, label])
String
Sets a timers and accepts an optional label. If none provided the timer will receive a unique label automatically.
Returns a string corresponding to the timer label.
label
String
Label corresponding to the timer. Each timer must have its own unique label.
const signale = require('signale');
signale.time();
//=> ▶ timer_0 Initialized timer...
signale.time();
//=> ▶ timer_1 Initialized timer...
signale.time('label');
//=> ▶ label Initialized timer...
timeEnd([, label])
Object
Deactivates the timer to which the given label corresponds. If no label is provided the most recent timer, that was created without providing a label, will be deactivated.
Returns an object {label, span}
holding the timer label and the total running time.
label
String
Label corresponding to the timer, each timer has its own unique label.
const signale = require('signale');
signale.time();
//=> ▶ timer_0 Initialized timer...
signale.time();
//=> ▶ timer_1 Initialized timer...
signale.time('label');
//=> ▶ label Initialized timer...
signale.timeEnd();
//=> ◼ timer_1 Timer run for: 2ms
signale.timeEnd();
//=> ◼ timer_0 Timer run for: 2ms
signale.timeEnd('label');
//=> ◼ label Timer run for: 2ms
disable()
Disables the logging functionality of all loggers belonging to a specific instance.
const signale = require('signale');
signale.success('foo');
//=> ✔ success foo
signale.disable();
signale.success('foo');
//=>
enable()
Enables the logging functionality of all loggers belonging to a specific instance.
const signale = require('signale');
signale.disable();
signale.success('foo');
//=>
signale.enable();
signale.success('foo');
//=> ✔ success foo
isEnabled()
Checks whether the logging functionality of a specific instance is enabled.
const signale = require('signale');
signale.success('foo');
//=> ✔ success foo
signale.isEnabled();
// => true
signale.disable();
signale.success('foo');
//=>
signale.isEnabled();
// => false
addSecrets(secrets)
Adds new secrets/sensitive-information to the targeted Signale instance.
secrets
(String|Number)[]
Array holding the secrets/sensitive-information to be filtered out.
const signale = require('signale');
signale.log('$ exporting USERNAME=%s', 'klaussinani');
//=> $ exporting USERNAME=klaussinani signale.addSecrets(['klaussinani']);
signale.log('$ exporting USERNAME=%s', 'klaussinani');
//=> $ exporting USERNAME=[secure]
clearSecrets()
Removes all secrets/sensitive-information from the targeted Signale instance.
const signale = require('signale');
signale.addSecrets(['klaussinani']);
signale.log('$ exporting USERNAME=%s', 'klaussinani');
//=> $ exporting USERNAME=[secure]
signale.clearSecrets();
signale.log('$ exporting USERNAME=%s', 'klaussinani');
//=> $ exporting USERNAME=klaussinani
For more info on how to contribute to the project, please read the contributing guidelines.
cd signale
npm install
or yarn install
npm test
or yarn test
View in detail all the packages and repositories that are using Signale here.
Author: Klaussinani
Source Code: https://github.com/klaussinani/signale
License: MIT license
1660547940
Easily set your terminal text color & styles.
NO_COLOR
friendly10
import { blue, bold, underline } from "colorette"
console.log(
blue("I'm blue"),
bold(blue("da ba dee")),
underline(bold(blue("da ba daa")))
)
Here's an example using template literals.
console.log(`
There's a ${underline(blue("house"))},
With a ${bold(blue("window"))},
And a ${blue("corvette")}
And everything is blue
`)
You can also nest styles without breaking existing color sequences.
console.log(bold(`I'm ${blue(`da ba ${underline("dee")} da ba`)} daa`))
Need to override terminal color detection? You can do that too.
import { createColors } from "colorette"
const { blue } = createColors({ useColor: false })
console.log(blue("Blue? Nope, nah"))
npm install colorette
See all supported colors.
import { blue } from "colorette"
blue("I'm blue") //=> \x1b[34mI'm blue\x1b[39m
Override terminal color detection via createColors({ useColor })
.
import { createColors } from "colorette"
const { blue } = createColors({ useColor: false })
true
if your terminal supports color, false
otherwise. Used internally, but exposed for convenience.
You can override color detection from the CLI by setting the --no-color
or --color
flags.
$ ./example.js --no-color | ./consumer.js
Or if you can't use CLI flags, by setting the NO_COLOR=
or FORCE_COLOR=
environment variables.
$ NO_COLOR= ./example.js | ./consumer.js
Colors | Background Colors | Bright Colors | Bright Background Colors | Modifiers |
---|---|---|---|---|
black | bgBlack | blackBright | bgBlackBright | dim |
red | bgRed | redBright | bgRedBright | bold |
green | bgGreen | greenBright | bgGreenBright | hidden |
yellow | bgYellow | yellowBright | bgYellowBright | italic |
blue | bgBlue | blueBright | bgBlueBright | underline |
magenta | bgMagenta | magentaBright | bgMagentaBright | |
cyan | bgCyan | cyanBright | bgCyanBright | reset |
white | bgWhite | whiteBright | bgWhiteBright | |
gray |
npm --prefix bench start
chalk 1,786,703 ops/sec
kleur 1,618,960 ops/sec
colors 646,823 ops/sec
ansi-colors 786,149 ops/sec
picocolors 2,871,758 ops/sec
+ colorette 3,002,751 ops/sec
Colorette started out in 2015 by @jorgebucaran as a lightweight alternative to Chalk and was introduced originally as Clor. Our terminal color detection logic borrows heavily from @sindresorhus and @Qix- work on Chalk. The idea of slicing strings to clear bleeding sequences was adapted from a similar technique used by @alexeyraspopov in picocolors. Thank you to all our contributors! <3
Author: jorgebucaran
Source Code: https://github.com/jorgebucaran/colorette
License: MIT license
1660320000
If you like your code verbose, you may use long function names:
final log = Sprint('Sample', productionMode: false);
log.debug('Debug message');
log.success('Success message');
log.info('Info message');
log.warn('Warning message');
log.severe('Severe message');
log.fatal('Fatal message');
If you prefer to be brief in your writing, use short function names instead:
final log = Sprint('Sample', productionMode: false);
log.d('Debug message');
log.s('Success message');
log.i('Info message');
log.w('Warning message');
log.sv('Severe message');
log.f('Fatal message');
Most of the time, however, you will simply need to use the Sprint instance name:
log('Info message');
The display of messages can be controlled using the quietMode
field. If set to true
, no messages will be printed.
log.quietMode = true;
log('This message will not be posted.');
log.quietMode = false;
log('However, this one *will* be.');
Run this command:
With Dart:
$ dart pub add sprint
With Flutter:
$ flutter pub add sprint
This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get
):
dependencies:
sprint: ^1.0.4
Alternatively, your editor might support dart pub get
or flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:sprint/sprint.dart';
example/example.dart
import 'package:sprint/sprint.dart';
class Server {
final Sprint log = Sprint('Server');
Future init() async {
doWork();
try {
doCrucialButErrorProneWork();
} on Exception catch (exception) {
return log.fatal('Failed to initialise server: $exception');
}
log.info('Initialised server');
}
void doWork() {}
void doCrucialButErrorProneWork() {}
}
Author: Wordcollector
Source Code: https://github.com/wordcollector/sprint
License: MIT license
1659526500
radian is an alternative console for the R program with multiline editing and rich syntax highlight. One would consider radian as a ipython clone for R, though its design is more aligned to julia.
;
to enter and <backspace>
to leave~
to enterjedi
)Requirements:
python
(version 3.6 or above) is also required to install radian. If your system doesn't come with a python distribution, it can be downloaded from https://www.python.org/downloads/ or https://conda.io/en/latest/miniconda.html.pip
is optional but it makes the installation a bit easier.# install released version
pip3 install -U radian
# to run radian
radian
# or the development version
pip3 install -U git+https://github.com/randy3k/radian
Alternatively, if you use conda or miniconda,
conda install -c conda-forge radian
You could alias r
to radian by putting
alias r="radian"
in ~/.bash_profile
such that r
would open radian and R
would still open the traditional R console. (R
is still useful, e.g, running R CMD BUILD
.)
radian can be customized by specifying the below options in various locations
$XDG_CONFIG_HOME/radian/profile
or $HOME/.config/radian/profile
(Unix)%USERPROFILE%/radian/profile
(Windows)$HOME/.radian_profile
(Unix)%USERPROFILE%/.radian_profile
(Windows).radian_profile
in the working directoryThe options could be also specified in the .Rprofile
files, however, it is not recommended because
packrat
or renv
.# Do not copy the whole configuration, just specify what you need!
# see https://help.farbox.com/pygments.html
# for a list of supported color schemes, default scheme is "native"
options(radian.color_scheme = "native")
# either `"emacs"` (default) or `"vi"`.
options(radian.editing_mode = "emacs")
# enable various emacs bindings in vi insert mode
options(radian.emacs_bindings_in_vi_insert_mode = FALSE)
# show vi mode state when radian.editing_mode is `vi`
options(radian.show_vi_mode_prompt = TRUE)
options(radian.vi_mode_prompt = "\033[0;34m[{}]\033[0m ")
# indent continuation lines
# turn this off if you want to copy code without the extra indentation;
# but it leads to less elegent layout
options(radian.indent_lines = TRUE)
# auto match brackets and quotes
options(radian.auto_match = TRUE)
# enable the [prompt_toolkit](https://python-prompt-toolkit.readthedocs.io/en/master/index.html) [`auto_suggest` feature](https://python-prompt-toolkit.readthedocs.io/en/master/pages/asking_for_input.html#auto-suggestion)
# this option is experimental and is known to break python prompt, use it with caution
options(radian.auto_suggest = FALSE)
# highlight matching bracket
options(radian.highlight_matching_bracket = FALSE)
# auto indentation for new line and curly braces
options(radian.auto_indentation = TRUE)
options(radian.tab_size = 4)
# pop up completion while typing
options(radian.complete_while_typing = TRUE)
# the minimum length of prefix to trigger auto completions
options(radian.completion_prefix_length = 2)
# timeout in seconds to cancel completion if it takes too long
# set it to 0 to disable it
options(radian.completion_timeout = 0.05)
# add spaces around equals in function argument completion
options(radian.completion_adding_spaces_around_equals = TRUE)
# automatically adjust R buffer size based on terminal width
options(radian.auto_width = TRUE)
# insert new line between prompts
options(radian.insert_new_line = TRUE)
# max number of history records
options(radian.history_size = 20000)
# where the global history is stored, environmental variables will be expanded
# note that "~" is expanded to %USERPROFILE% or %HOME% in Windows
options(radian.global_history_file = "~/.radian_history")
# the filename that local history is stored, this file would be used instead of
# `radian.global_history_file` if it exists in the current working directory
options(radian.local_history_file = ".radian_history")
# when using history search (ctrl-r/ctrl-s in emacs mode), do not show duplicate results
options(radian.history_search_no_duplicates = FALSE)
# ignore case in history search
options(radian.history_search_ignore_case = FALSE)
# do not save debug browser commands such as `Q` in history
options(radian.history_ignore_browser_commands = TRUE)
# custom prompt for different modes
options(radian.prompt = "\033[0;34mr$>\033[0m ")
options(radian.shell_prompt = "\033[0;31m#!>\033[0m ")
options(radian.browse_prompt = "\033[0;33mBrowse[{}]>\033[0m ")
# stderr color format
options(radian.stderr_format = "\033[0;31m{}\033[0m")
# enable reticulate prompt and trigger `~`
options(radian.enable_reticulate_prompt = TRUE)
# allows user defined shortcuts, these keys should be escaped when send through the terminal.
# In the following example, `esc` + `-` sends `<-` and `esc` + `m` sends `%>%`.
# Note that in some terminals, you could mark `alt` as `escape` so you could use `alt` + `-` instead.
options(radian.escape_key_map = list(
list(key = "-", value = " <- "),
list(key = "m", value = " %>% ")
))
The latest version of R supports Unicode codepage directly. However, radian relies on Python and Python doesn't support Unicode in the way that R supports it. A workaround could be found here: https://github.com/randy3k/radian/issues/269#issuecomment-1169663251
It is expected. radian
runs on python and the python runtime used by radian is forced in reticulate. reticulate::py_config()
gives the note:
NOTE: Python version was forced by the current process
In order to use radian with another python runtime, you will need to install radian
on that python environment.
There are serveral options.
--r-binary
, i.e., radian --r-binary=/path/to/R
PATH
variableR_BINARY
could also be used to specify the path to R.R_HOME
could also be used to specify R home directory. Note that it is should be set as the result of R.home()
, not the directory where R
is located. For example, in Unix$ env R_HOME=/usr/local/lib/R radian
Please also make sure that R was installed with the R shared library libR.so
or libR.dylib
or libR.dll
. On Linux, the configure flag ./configure --enable-R-shlib
may be needed to install R from the source. Do not forget to make clean
to force the recompilation of the files with the correct compiler options.
If you encounter
The package setup script has attempted to modify files on your system that are not within the EasyInstall build area.
Please update your setuptools by
pip install -U setuptools
radian maintains its own history file .radian_history
and doesn't use the .Rhistory
file. A local .radian_history
is used if it is found in the launch directory. Otherwise, the global history file ~/.radian_history
would be used. To override the default behavior, you could launch radian with the options: radian --local-history
, radian --global-history
or radian --no-history
.
radian only provides a frontend to the R program, the actual running eventloop is the same as that of the traditional R console. There is no performance sacrifice (or gain) while using this modern command line interface.
Put
let R_app = "radian"
let R_cmd = "R"
let R_hl_term = 0
let R_args = [] " if you had set any
let R_bracketed_paste = 1
in your vim config.
reticulate
Auto CompletionsTo enable reticulate prompt completions, make sure that jedi
is installed.
pip install jedi
Alternatively, if you use conda,
conda install -c conda-forge jedi
It maybe caused by the invalid terminal size, try running stty size
in your terminal to see if it returns a correct size. You could change the values of it from the environmental variables $COLUMNS
and $LINES
when you log-in the docker container.
docker exec -it <container> bash -c "stty cols $COLUMNS rows $LINES && bash"
radian is powered by (π)thon.
radian wouldn't be possible without the creative work prompt_toolkit by Jonathan Slenders.
Author: Randy3k
Source Code: https://github.com/randy3k/radian
License: MIT license
1659272280
Laravel Langman
Langman is a language files manager in your artisan console, it helps you search, update, add, and remove translation lines with ease. Taking care of a multilingual interface is not a headache anymore.
Begin by installing the package through Composer. Run the following command in your terminal:
$ composer require themsaid/laravel-langman
Once done, add the following line in your providers array of config/app.php
:
Themsaid\Langman\LangmanServiceProvider::class
This package has a single configuration option that points to the resources/lang
directory, if only you need to change the path then publish the config file:
php artisan vendor:publish --provider="Themsaid\Langman\LangmanServiceProvider"
php artisan langman:show users
You get:
+---------+---------------+-------------+
| key | en | nl |
+---------+---------------+-------------+
| name | name | naam |
| job | job | baan |
+---------+---------------+-------------+
php artisan langman:show users.name
Brings only the translation of the name
key in all languages.
php artisan langman:show users.name.first
Brings the translation of a nested key.
php artisan langman:show package::users.name
Brings the translation of a vendor package language file.
php artisan langman:show users --lang=en,it
Brings the translation of only the "en" and "it" languages.
php artisan langman:show users.nam -c
Brings only the translation lines with keys matching the given key via close match, so searching for nam
brings values for keys like (name
, username
, branch_name_required
, etc...).
In the table returned by this command, if a translation is missing it'll be marked in red.
php artisan langman:find 'log in first'
You get a table of language lines where any of the values matches the given phrase by close match.
php artisan langman:sync
This command will look into all files in resources/views
and app
and find all translation keys that are not covered in your translation files, after that it appends those keys to the files with a value equal to an empty string.
php artisan langman:missing
It'll collect all the keys that are missing in any of the languages or has values equals to an empty string, prompt asking you to give a translation for each, and finally save the given values to the files.
php artisan langman:trans users.name
php artisan langman:trans users.name.first
php artisan langman:trans users.name --lang=en
php artisan langman:trans package::users.name
Using this command you may set a language key (plain or nested) for a given group, you may also specify which language you wish to set leaving the other languages as is.
This command will add a new key if not existing, and updates the key if it is already there.
php artisan langman:remove users.name
php artisan langman:remove package::users.name
It'll remove that key from all language files.
php artisan langman:rename users.name full_name
This will rename users.name
to be users.full_name
, the console will output a list of files where the key used to exist.
langman:sync
, langman:missing
, langman:trans
, and langman:remove
will update your language files by writing them completely, meaning that any comments or special styling will be removed, so I recommend you backup your files.
If you want a web interface to manage your language files instead, I recommend Laravel 5 Translation Manager by Barry vd. Heuvel.
Author: Themsaid
Source Code: https://github.com/themsaid/laravel-langman
License: MIT license
1658618040
Just a simple logging module for your Electron or NW.js application. No dependencies. No complicated configuration. Just require and use. Also, it can be used without Electron in any node.js application.
By default, it writes logs to the following locations:
~/.config/{app name}/logs/{process type}.log
~/Library/Logs/{app name}/{process type}.log
%USERPROFILE%\AppData\Roaming\{app name}\logs\{process type}.log
Install with npm:
npm install electron-log
const log = require('electron-log');
log.info('Hello, log');
log.warn('Some problem appears');
If you would like to upgrade to the latest version, read the migration guide and the changelog.
electron-log supports the following log levels:
error, warn, info, verbose, debug, silly
nodeIntegration
If you've got an error like require is not defined
in a renderer process, read the nodeIntegration section.
Transport is a simple function which does some work with log message. By default, two transports are active: console and file.
If you change some transport options, make sure you apply the changes both in main and renderer processes.
You can set transport options or use methods using:
log.transports.console.format = '{h}:{i}:{s} {text}';
log.transports.file.getFile();
Just prints a log message to application console (main process) or to DevTools console (renderer process).
Options
'%c{h}:{i}:{s}.{ms}%c › {text}'
(main), '{h}:{i}:{s}.{ms} › {text}'
(renderer)null
The file transport writes log messages to a file.
Options
'[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}] {text}'
log.transports.file.resolvePath = () => path.join(APP_DATA, 'logs/main.log');
Read more about file transport.
When logging inside renderer process, it also shows log in application console and vice versa. This transport can impact on performance, so it's disabled by default for packaged application.
If you don't use electron-log in the main process but want to show renderer logs in the console, add require('electron-log')
somewhere in the main code.
Options
Sends a JSON POST request with LogMessage
in the body to the specified url.
Options
Read more about remote transport.
Just set level property to false, for example:
log.transports.file.level = false;
log.transports.console.level = false;
Transport is just a function (msg: LogMessage) => void
, so you can easily override/add your own transport. More info.
Sometimes it's helpful to use electron-log instead of default console
. It's pretty easy:
console.log = log.log;
If you would like to override other functions like error
, warn
and so on:
Object.assign(console, log.functions);
Colors can be used for both main and DevTools console.
log.info('%cRed text. %cGreen text', 'color: red', 'color: green')
Available colors:
For DevTools console you can use other CSS properties.
electron-log can catch and log unhandled errors/rejected promises:
log.catchErrors(options?)
;
In some situations, you may want to get more control over logging. Hook is a function which is called on each transport call.
(message: LogMessage, transport: Transport) => LogMessage
You can create multiple logger instances with different settings:
const electronLog = require('electron-log');
const log = electronLog.create('anotherInstance');
const log = require('electron-log');
const userLog = log.scope('user');
userLog.info('message with user scope');
// Prints 12:12:21.962 (user) › message with user scope
It's possible to use the module with Web Worker. However, ipc transport is not active, so log messages from worker are not displayed in the main app console.
Author: Megahertz
Source Code: https://github.com/megahertz/electron-log
License: MIT license