Custom opstring parsing when multiple instances of same flag is applied? - node.js

I have a command line program where I want to generate a picture given multiple arguments, where the order of the arguments should be respected, and duplicate arguments are allowed
Are there any node.js optstring parsers that would allow for this?
I would like to have something like
generate_picture --red 100 --yellow 200 --red 100 --width 500
And then it generates a "flag" with a red 100px band on top, then a 200px band of yellow, and then another 100px red band, all applied with width 500px
My program doesn't literally do that but it is similar
I think the ideal form that my program would receive these arguments would be an array of arrays like this
[
['red', 100],
['yellow', 200],
['red', 100],
['width', 500]
]
I would probably up-front scan this array-of-arrays for the things i expect to only be applied once like width
I suppose now that I write it out, it might not be too hard to manually parse the process.argv array to get it into this state but curious if there are any options available already

To help my particular circumstance I made this utility function
function parseArgv(argv) {
const map = [];
while (argv.length) {
const val = argv[0].slice(2);
argv = argv.slice(1);
const next = argv.findIndex((arg) => arg.startsWith("-"));
if (next !== -1) {
map.push([val, argv.slice(0, next)]);
argv = argv.slice(next);
} else {
map.push([val, argv]);
break;
}
}
return map;
}
Example usage
test("parse", () => {
expect(
parseArgv(
"--bam file1.bam color:red --vcf variants.vcf --bam file2.bam --defaultSession --out out.svg --fullSvg".split(
" "
)
)
).toEqual([
["bam", ["file1.bam", "color:red"]],
["vcf", ["variants.vcf"]],
["bam", ["file2.bam"]],
["defaultSession", []],
["out", ["out.svg"]],
["fullSvg", []],
]);
});
Then post processing can make a little more sense of this, but this utility function was helpful for my purposes in a way that was not achievable with yargs or other node optstring parsers

Related

json_agg result from NodeJS application code is different than the same query in pgAdmin [duplicate]

I have this object:
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
But when I try to show it using console.log(myObject), I receive this output:
{ a: 'a', b: { c: 'c', d: { e: 'e', f: [Object] } } }
How can I get the full object, including the content of property f?
You need to use util.inspect():
const util = require('util')
console.log(util.inspect(myObject, {showHidden: false, depth: null, colors: true}))
// alternative shortcut
console.log(util.inspect(myObject, false, null, true /* enable colors */))
Outputs
{ a: 'a', b: { c: 'c', d: { e: 'e', f: { g: 'g', h: { i: 'i' } } } } }
You can use JSON.stringify, and get some nice indentation as well as perhaps easier to remember syntax.
console.log(JSON.stringify(myObject, null, 4));
{
"a": "a",
"b": {
"c": "c",
"d": {
"e": "e",
"f": {
"g": "g",
"h": {
"i": "i"
}
}
}
}
}
The third argument sets the indentation level, so you can adjust that as desired.
More detail here in JSON stringify MDN docs if needed.
A compilation of the many useful answers from (at least) Node.js v0.10.33 (stable) / v0.11.14 (unstable) presumably through (at least) v7.7.4 (the version current as of the latest update to this answer). Tip of the hat to Rory O'Kane for his help.
tl;dr
To get the desired output for the example in the question, use console.dir():
console.dir(myObject, { depth: null }); // `depth: null` ensures unlimited recursion
Why not util.inspect()? Because it’s already at the heart of diagnostic output: console.log() and console.dir() as well as the Node.js REPL use util.inspect() implicitly. It’s generally not necessary to require('util') and call util.inspect() directly.
Details below.
console.log() (and its alias, console.info()):
If the 1st argument is NOT a format string: util.inspect() is automatically applied to every argument:
o = { one: 1, two: 'deux', foo: function(){} }; console.log(o, [1,2,3]) // -> '{ one: 1, two: 'deux', foo: [Function] } [ 1, 2, 3 ]'
Note that you cannot pass options through util.inspect() in this case, which implies 2 notable limitations:
Structural depth of the output is limited to 2 levels (the default).
Since you cannot change this with console.log(), you must instead use console.dir(): console.dir(myObject, { depth: null } prints with unlimited depth; see below.
You can’t turn syntax coloring on.
If the 1st argument IS a format string (see below): uses util.format() to print the remaining arguments based on the format string (see below); e.g.:
o = { one: 1, two: 'deux', foo: function(){} }; console.log('o as JSON: %j', o) // -> 'o as JSON: {"one":1,"two":"deux"}'
Note:
There is NO placeholder for representing objects util.inspect()-style.
JSON generated with %j is NOT pretty-printed.
console.dir():
Accepts only 1 argument to inspect, and always applies util.inspect() – essentially, a wrapper for util.inspect() without options by default; e.g.:
o = { one: 1, two: 'deux', foo: function(){} }; console.dir(o); // Effectively the same as console.log(o) in this case.
Node.js v0.11.14+: The optional 2nd argument specifies options for util.inspect() – see below; e.g.:
console.dir({ one: 1, two: 'deux'}, { colors: true }); // Node 0.11+: Prints object representation with syntax coloring.
The REPL: implicitly prints any expression's return value with util.inspect() with syntax coloring;
i.e., just typing a variable's name and hitting Enter will print an inspected version of its value; e.g.:
o = { one: 1, two: 'deux', foo: function(){} } // The REPL echoes the object definition with syntax coloring.
util.inspect() automatically pretty-prints object and array representations, but produces multiline output only when needed.
The pretty-printing behavior can be controlled by the compact property in the optional options argument; false uses multi-line output unconditionally, whereas true disables pretty-printing altogether; it can also be set to a number (the default is 3) to control the conditional multi-line behavior – see the docs.
By default, output is wrapped at around 60 characters thanks, Shrey
, regardless of whether the output is sent to a file or a terminal. In practice, since line breaks only happen at property boundaries, you will often end up with shorter lines, but they can also be longer (e.g., with long property values).
In v6.3.0+ you can use the breakLength option to override the 60-character limit; if you set it to Infinity, everything is output on a single line.
If you want more control over pretty-printing, consider using JSON.stringify() with a 3rd argument, but note the following:
Fails with objects that have circular references, such as module in the global context.
Methods (functions) will by design NOT be included.
You can't opt into showing hidden (non-enumerable) properties.
Example call:
JSON.stringify({ one: 1, two: 'deux', three: true}, undefined, 2); // creates a pretty-printed multiline JSON representation indented with 2 spaces
util.inspect() options object (2nd argument):
An optional options object may be passed that alters certain aspects of the formatted string; some of the properties supported are:
See the latest Node.js docs for the current, full list.
showHidden
if true, then the object's non-enumerable properties [those designated not to show up when you use for keys in obj or Object.keys(obj)] will be shown too. Defaults to false.
depth
tells inspect how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. Defaults to 2. To make it recurse indefinitely, pass null.
colors
if true, then the output will be styled with ANSI color codes. Defaults to false. Colors are customizable [… – see link].
customInspect
if false, then custom inspect() functions defined on the objects being inspected won't be called. Defaults to true.
util.format() format-string placeholders (1st argument)
Some of the supported placeholders are:
See the latest Node.js docs for the current, full list.
%s – String.
%d – Number (both integer and float).
%j – JSON.
%% – single percent sign (‘%’). This does not consume an argument.
Another simple method is to convert it to json
console.log('connection : %j', myObject);
Since Node.js 6.4.0, this can be elegantly solved with util.inspect.defaultOptions:
require("util").inspect.defaultOptions.depth = null;
console.log(myObject);
Try this:
console.dir(myObject,{depth:null})
Both of these usages can be applied:
// more compact, and colour can be applied (better for process managers logging)
console.dir(queryArgs, { depth: null, colors: true });
// get a clear list of actual values
console.log(JSON.stringify(queryArgs, undefined, 2));
perhaps console.dir is all you need.
http://nodejs.org/api/console.html#console_console_dir_obj
Uses util.inspect on obj and prints resulting string to stdout.
use util option if you need more control.
A good way to inspect objects is to use node --inspect option with Chrome DevTools for Node.
node.exe --inspect www.js
Open chrome://inspect/#devices in chrome and click Open dedicated DevTools for Node
Now every logged object is available in inspector like regular JS running in chrome.
There is no need to reopen inspector, it connects to node automatically as soon as node starts or restarts. Both --inspect and Chrome DevTools for Node may not be available in older versions of Node and Chrome.
You can also do
console.log(JSON.stringify(myObject, null, 3));
I think this could be useful for you.
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
console.log(JSON.stringify(myObject, null, '\t'));
As mentioned in this answer:
JSON.stringify's third parameter defines white-space insertion for
pretty-printing. It can be a string or a number (number of spaces).
JSON.stringify()
let myVar = {a: {b: {c: 1}}};
console.log(JSON.stringify( myVar, null, 4 ))
Great for deep inspection of data objects. This approach works on nested arrays and nested objects with arrays.
You can simply add an inspect() method to your object which will override the representation of object in console.log messages
eg:
var myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
myObject.inspect = function(){ return JSON.stringify( this, null, ' ' ); }
then, your object will be represented as required in both console.log and node shell
Update:
object.inspect has been deprecated ( https://github.com/nodejs/node/issues/15549). Use myObject[util.inspect.custom] instead:
const util = require('util')
var myObject = {
/* nested properties not shown */
}
myObject[util.inspect.custom] = function(){ return JSON.stringify( this, null, 4 ); }
console.log(util.inspect(myObject))
Use a logger
Don't try to reinvent the wheel
util.inspect(), JSON.stringify() and console.dir() are useful tools for logging an object while playing in the browser console.
If you are serious about Node.js development, you should definitely use a logger. Using it you can add all the logs you want for debugging and monitoring your application. Then just change the logging level of your logger to keep only the production logs visible.
Additionaly they have already solved all the annoying issues related to logging, like: circular objects, formatting, log levels, multiple outputs and performance.
Use a modern logger
pino is a fast and modern logger for Node.js that has sane defaults to handle circular object/references like depthLimit and edgeLimit. It supports child loggers, transports and a pretty printed output.
Moreover, it has 8 default logging levels that you can customize using the customLevels option:
fatal
error
warn
info
debug
trace
silent
Install it
npm install pino
Use it
const logger = require('pino')()
logger.info('hello world')
Configure it
const logger = pino({
depthLimit: 10,
edgeLimit: 200,
customLevels: {
foo: 35
}
});
logger.foo('hi')
A simple trick would be use debug module to add DEBUG_DEPTH=null as environment variable when running the script
Ex.
DEBUG=* DEBUG_DEPTH=null node index.js
In you code
const debug = require('debug');
debug("%O", myObject);
If you're looking for a way to show the hidden items in you array, you got to pass maxArrayLength: Infinity
console.log(util.inspect(value, { maxArrayLength: Infinity }));
The node REPL has a built-in solution for overriding how objects are displayed, see here.
The REPL module internally uses util.inspect(), when printing values.
However, util.inspect delegates the call to the object's inspect()
function, if it has one.
Easiest option:
console.log('%O', myObject);
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
console.log(JSON.stringify(myObject));
Output:
{"a":"a","b":{"c":"c","d":{"e":"e","f":{"g":"g","h":{"i":"i"}}}}}

Why would a function called from another not show in the profile output of a node app?

I have a NodeJS program. This is a trimmed down version of a much larger program with a lot of complexity that's irrelevant to this question removed. It goes through lists looking for matching objects:
/**
* Checks that the given attributes are defined in the given dictionaries
* and have the same value
*/
function areDefinedAndEqual(a, b, keys) {
return (
a &&
b &&
keys
.map(function (k) {
return a[k] && b[k] && a[k] === b[k]
})
.reduce(function (a, b) {
return a && b
}, true)
)
}
function calculateOrder() {
const matchingRules = [
{
desc: 'stuff, more stuff and different stuff',
find: (po, dp) => areDefinedAndEqual(po, dp, ['stuff', 'more_stuff', 'different_stuff'])
},
{
desc: 'stuff and different stuff',
find: (po, dp) => areDefinedAndEqual(po, dp, ['stuff', 'different_stuff'])
},
{
desc: 'just stuff',
find: (po, dp) => areDefinedAndEqual(po, dp, ['stuff'])
}
]
let listOfStuff = []
listOfStuff[999] = { stuff: 'Hello' }
listOfStuff[9999] = { stuff: 'World' }
listOfStuff[99999] = { stuff: 'Hello World' }
// Run through lots of objects running through different rules to
// find things that look similar to what we're searching for
for (let i = 0; i < 100000000; i++) {
for (let j = 0; j < matchingRules.length; j++) {
if (matchingRules[j].find({ stuff: 'Hello World' }, listOfStuff[i])) {
console.log(`Found match at position ${i} on ${matchingRules[j].desc}`)
}
}
}
}
calculateOrder()
Now all calculateOrder does is repeatedly call functions listed under matchingRules which in turn call areDefinedAndEqual which does some actual checking.
Now if I run this as follows:
richard#sophia:~/cc/sheetbuilder (main) $ node --prof fred.js
Found match at position 99999 on just stuff
richard#sophia:~/cc/sheetbuilder (main) $
I get just what I'd expect. So far so good.
I can then run the profile output through prof-process to get something more readable.
node --prof-process isolate-0x57087f0-56563-v8.log
However if I look at the output, I see this:
[JavaScript]:
ticks total nonlib name
4197 46.0% 89.0% LazyCompile: *calculateOrder /home/richard/cogcred/eng-data_pipeline_misc/sheetbuilder/fred.js:19:24
All the time is being spent in calculateOrder. I'd expect to see a large %age of the time spent in the various "find" functions and in areDefinedAndEqual but I don't. There's no mention of any of them at all. Why? Are they potentially being optimized out / inlined in some way? If so, how do I begin to debug that? Or is there some restrictions on certain functions not showing in the output? In which case, where are those retrictions defined? Any pointers would be much appreciated.
I'm running Node v16.5.0
Functions show up in the profile when tick samples have been collected for them. Since sample-based profiling is a statistical affair, it could happen that a very short-running function just wasn't sampled.
In the case at hand, inlining is the more likely answer. Running node with --trace-turbo-inlining spits out a bunch of information about inlining decisions.
If I run the example you posted, I see areDefinedEqual getting inlined into find, and accordingly find (and calculateOrder) are showing up high on the profile. Looking closely, in the particular run I profiled, areDefinedEqual was caught by a single profiler tick -- before it got inlined.

Query nested objects mongoose [duplicate]

I have this object:
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
But when I try to show it using console.log(myObject), I receive this output:
{ a: 'a', b: { c: 'c', d: { e: 'e', f: [Object] } } }
How can I get the full object, including the content of property f?
You need to use util.inspect():
const util = require('util')
console.log(util.inspect(myObject, {showHidden: false, depth: null, colors: true}))
// alternative shortcut
console.log(util.inspect(myObject, false, null, true /* enable colors */))
Outputs
{ a: 'a', b: { c: 'c', d: { e: 'e', f: { g: 'g', h: { i: 'i' } } } } }
You can use JSON.stringify, and get some nice indentation as well as perhaps easier to remember syntax.
console.log(JSON.stringify(myObject, null, 4));
{
"a": "a",
"b": {
"c": "c",
"d": {
"e": "e",
"f": {
"g": "g",
"h": {
"i": "i"
}
}
}
}
}
The third argument sets the indentation level, so you can adjust that as desired.
More detail here in JSON stringify MDN docs if needed.
A compilation of the many useful answers from (at least) Node.js v0.10.33 (stable) / v0.11.14 (unstable) presumably through (at least) v7.7.4 (the version current as of the latest update to this answer). Tip of the hat to Rory O'Kane for his help.
tl;dr
To get the desired output for the example in the question, use console.dir():
console.dir(myObject, { depth: null }); // `depth: null` ensures unlimited recursion
Why not util.inspect()? Because it’s already at the heart of diagnostic output: console.log() and console.dir() as well as the Node.js REPL use util.inspect() implicitly. It’s generally not necessary to require('util') and call util.inspect() directly.
Details below.
console.log() (and its alias, console.info()):
If the 1st argument is NOT a format string: util.inspect() is automatically applied to every argument:
o = { one: 1, two: 'deux', foo: function(){} }; console.log(o, [1,2,3]) // -> '{ one: 1, two: 'deux', foo: [Function] } [ 1, 2, 3 ]'
Note that you cannot pass options through util.inspect() in this case, which implies 2 notable limitations:
Structural depth of the output is limited to 2 levels (the default).
Since you cannot change this with console.log(), you must instead use console.dir(): console.dir(myObject, { depth: null } prints with unlimited depth; see below.
You can’t turn syntax coloring on.
If the 1st argument IS a format string (see below): uses util.format() to print the remaining arguments based on the format string (see below); e.g.:
o = { one: 1, two: 'deux', foo: function(){} }; console.log('o as JSON: %j', o) // -> 'o as JSON: {"one":1,"two":"deux"}'
Note:
There is NO placeholder for representing objects util.inspect()-style.
JSON generated with %j is NOT pretty-printed.
console.dir():
Accepts only 1 argument to inspect, and always applies util.inspect() – essentially, a wrapper for util.inspect() without options by default; e.g.:
o = { one: 1, two: 'deux', foo: function(){} }; console.dir(o); // Effectively the same as console.log(o) in this case.
Node.js v0.11.14+: The optional 2nd argument specifies options for util.inspect() – see below; e.g.:
console.dir({ one: 1, two: 'deux'}, { colors: true }); // Node 0.11+: Prints object representation with syntax coloring.
The REPL: implicitly prints any expression's return value with util.inspect() with syntax coloring;
i.e., just typing a variable's name and hitting Enter will print an inspected version of its value; e.g.:
o = { one: 1, two: 'deux', foo: function(){} } // The REPL echoes the object definition with syntax coloring.
util.inspect() automatically pretty-prints object and array representations, but produces multiline output only when needed.
The pretty-printing behavior can be controlled by the compact property in the optional options argument; false uses multi-line output unconditionally, whereas true disables pretty-printing altogether; it can also be set to a number (the default is 3) to control the conditional multi-line behavior – see the docs.
By default, output is wrapped at around 60 characters thanks, Shrey
, regardless of whether the output is sent to a file or a terminal. In practice, since line breaks only happen at property boundaries, you will often end up with shorter lines, but they can also be longer (e.g., with long property values).
In v6.3.0+ you can use the breakLength option to override the 60-character limit; if you set it to Infinity, everything is output on a single line.
If you want more control over pretty-printing, consider using JSON.stringify() with a 3rd argument, but note the following:
Fails with objects that have circular references, such as module in the global context.
Methods (functions) will by design NOT be included.
You can't opt into showing hidden (non-enumerable) properties.
Example call:
JSON.stringify({ one: 1, two: 'deux', three: true}, undefined, 2); // creates a pretty-printed multiline JSON representation indented with 2 spaces
util.inspect() options object (2nd argument):
An optional options object may be passed that alters certain aspects of the formatted string; some of the properties supported are:
See the latest Node.js docs for the current, full list.
showHidden
if true, then the object's non-enumerable properties [those designated not to show up when you use for keys in obj or Object.keys(obj)] will be shown too. Defaults to false.
depth
tells inspect how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. Defaults to 2. To make it recurse indefinitely, pass null.
colors
if true, then the output will be styled with ANSI color codes. Defaults to false. Colors are customizable [… – see link].
customInspect
if false, then custom inspect() functions defined on the objects being inspected won't be called. Defaults to true.
util.format() format-string placeholders (1st argument)
Some of the supported placeholders are:
See the latest Node.js docs for the current, full list.
%s – String.
%d – Number (both integer and float).
%j – JSON.
%% – single percent sign (‘%’). This does not consume an argument.
Another simple method is to convert it to json
console.log('connection : %j', myObject);
Since Node.js 6.4.0, this can be elegantly solved with util.inspect.defaultOptions:
require("util").inspect.defaultOptions.depth = null;
console.log(myObject);
Try this:
console.dir(myObject,{depth:null})
Both of these usages can be applied:
// more compact, and colour can be applied (better for process managers logging)
console.dir(queryArgs, { depth: null, colors: true });
// get a clear list of actual values
console.log(JSON.stringify(queryArgs, undefined, 2));
perhaps console.dir is all you need.
http://nodejs.org/api/console.html#console_console_dir_obj
Uses util.inspect on obj and prints resulting string to stdout.
use util option if you need more control.
A good way to inspect objects is to use node --inspect option with Chrome DevTools for Node.
node.exe --inspect www.js
Open chrome://inspect/#devices in chrome and click Open dedicated DevTools for Node
Now every logged object is available in inspector like regular JS running in chrome.
There is no need to reopen inspector, it connects to node automatically as soon as node starts or restarts. Both --inspect and Chrome DevTools for Node may not be available in older versions of Node and Chrome.
You can also do
console.log(JSON.stringify(myObject, null, 3));
I think this could be useful for you.
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
console.log(JSON.stringify(myObject, null, '\t'));
As mentioned in this answer:
JSON.stringify's third parameter defines white-space insertion for
pretty-printing. It can be a string or a number (number of spaces).
JSON.stringify()
let myVar = {a: {b: {c: 1}}};
console.log(JSON.stringify( myVar, null, 4 ))
Great for deep inspection of data objects. This approach works on nested arrays and nested objects with arrays.
You can simply add an inspect() method to your object which will override the representation of object in console.log messages
eg:
var myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
myObject.inspect = function(){ return JSON.stringify( this, null, ' ' ); }
then, your object will be represented as required in both console.log and node shell
Update:
object.inspect has been deprecated ( https://github.com/nodejs/node/issues/15549). Use myObject[util.inspect.custom] instead:
const util = require('util')
var myObject = {
/* nested properties not shown */
}
myObject[util.inspect.custom] = function(){ return JSON.stringify( this, null, 4 ); }
console.log(util.inspect(myObject))
Use a logger
Don't try to reinvent the wheel
util.inspect(), JSON.stringify() and console.dir() are useful tools for logging an object while playing in the browser console.
If you are serious about Node.js development, you should definitely use a logger. Using it you can add all the logs you want for debugging and monitoring your application. Then just change the logging level of your logger to keep only the production logs visible.
Additionaly they have already solved all the annoying issues related to logging, like: circular objects, formatting, log levels, multiple outputs and performance.
Use a modern logger
pino is a fast and modern logger for Node.js that has sane defaults to handle circular object/references like depthLimit and edgeLimit. It supports child loggers, transports and a pretty printed output.
Moreover, it has 8 default logging levels that you can customize using the customLevels option:
fatal
error
warn
info
debug
trace
silent
Install it
npm install pino
Use it
const logger = require('pino')()
logger.info('hello world')
Configure it
const logger = pino({
depthLimit: 10,
edgeLimit: 200,
customLevels: {
foo: 35
}
});
logger.foo('hi')
A simple trick would be use debug module to add DEBUG_DEPTH=null as environment variable when running the script
Ex.
DEBUG=* DEBUG_DEPTH=null node index.js
In you code
const debug = require('debug');
debug("%O", myObject);
If you're looking for a way to show the hidden items in you array, you got to pass maxArrayLength: Infinity
console.log(util.inspect(value, { maxArrayLength: Infinity }));
The node REPL has a built-in solution for overriding how objects are displayed, see here.
The REPL module internally uses util.inspect(), when printing values.
However, util.inspect delegates the call to the object's inspect()
function, if it has one.
Easiest option:
console.log('%O', myObject);
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
console.log(JSON.stringify(myObject));
Output:
{"a":"a","b":{"c":"c","d":{"e":"e","f":{"g":"g","h":{"i":"i"}}}}}

Train classifier (natural - NLP) on node.js for unexpected sentences

Some context: Node.js, Bot, natural module.
I would like to build a Bot and I am using the natural module in order to parse and overall classify the user input.
var classifier = new natural.BayesClassifier();
classifier.addDocument('Hi', 'welcome');
classifier.addDocument('Hello', 'welcome');
classifier.addDocument('Hey', 'welcome');
classifier.addDocument('Good', 'welcome');
...
//back to home
classifier.addDocument('go back to home', 'back2home');
classifier.addDocument('go back home', 'back2home');
classifier.addDocument('return', 'back2home');
classifier.addDocument('return to home', 'back2home');
...
classifier.train();
...
classifier.classify(text);
Those tests work fine:
"I would like to go back home" => back2home
"Hi" => welcome
All good, but what if the user text contains something such as: "bla bla bla", I want to get a way to know that the that the text not fits enough in any of the above cases. "bla bla bla" returns me => welcome, but actually i would like it return something such "unknown"/not understood.
It is a way to "train" the classifier in such a way?
Thanks.
You can use the getClassifications() method to get a list of classifications and the associated score, or 'confidence', with it. From that list you can determine which, if any, it best matches. Ex:
console.log(classifier.getClassifications('blah blah blah'));
Output:
[ { label: 'welcome', value: 0.5 },
{ label: 'back2home', value: 0.5 } ]
This example isn't a great one but you can see that it doesn't match any one label very well. The higher the value the higher the confidence.
You can check the value of it to ensure that it is above a certain level. I like to use 0.8 as my check value. Loop through the results.
const results = classifier.getClassifications('blah blah blah');
let intents = [];
// Check for confidence greater than 8
results.forEach((result) => {
if(result.value > 0.8) {
intents.push(result);
}
});
// Sort intents array by object.value
intents.sort((a,b) => {
if(a.value < b.value) {
return -1;
}
if(a.value > b.value) {
return 1;
}
return 0;
});
You now have an array of intents with confidence greater than 0.8, sorted descending by their confidence score.
More information at https://github.com/NaturalNode/natural#classifiers
Credit for sorting function Sort array of objects by string property value in JavaScript

How to change node.js's console font color?

I had to change the console background color to white because of eye problems, but the font is gray colored and it makes the messages unreadable. How can I change it?
Below you can find colors reference of text to command when running node.js application:
console.log('\x1b[36m%s\x1b[0m', 'I am cyan'); //cyan
console.log('\x1b[33m%s\x1b[0m', stringToMakeYellow); //yellow
Note %s is where in the string (the second argument) gets injected. \x1b[0m resets the terminal color so it doesn't continue to be the chosen color anymore after this point.
Colors reference
Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"
FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"
FgGray = "\x1b[90m"
BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
BgGray = "\x1b[100m"
EDIT:
For example, \x1b[31m is an escape sequence that will be intercepted by your terminal and instructs it to switch to the red color. In fact, \x1b is the code for the non-printable control character escape. Escape sequences dealing only with colors and styles are also known as ANSI escape code and are standardized, so therefore they (should) work on any platform.
Wikipedia has a nice comparison of how different terminals display colors
https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
There are multiple packages available for formatting console text in Node.js. The most popular are:
chalk —
cli-color —
colors — > EDIT: colors no longer recommended as it has denial of service vulnerability
see: https://snyk.io/blog/open-source-npm-packages-colors-faker/ for details
Usage:
CHALK:
const chalk = require('chalk');
console.log(chalk.red('Text in red'));
CLI-COLOR:
const clc = require('cli-color');
console.log(clc.red('Text in red'));
If you want to change the colors directly yourself without a module try
console.log('\x1b[36m', 'sometext' ,'\x1b[0m');
First \x1b[36m to change the colors to 36 and then back to terminal color 0.
Here's a list of ANSI color codes
This is a list of available colours (both background and foreground) in the console with some available actions (like reset, reverse, etc).
const colours = {
reset: "\x1b[0m",
bright: "\x1b[1m",
dim: "\x1b[2m",
underscore: "\x1b[4m",
blink: "\x1b[5m",
reverse: "\x1b[7m",
hidden: "\x1b[8m",
fg: {
black: "\x1b[30m",
red: "\x1b[31m",
green: "\x1b[32m",
yellow: "\x1b[33m",
blue: "\x1b[34m",
magenta: "\x1b[35m",
cyan: "\x1b[36m",
white: "\x1b[37m",
gray: "\x1b[90m",
crimson: "\x1b[38m" // Scarlet
},
bg: {
black: "\x1b[40m",
red: "\x1b[41m",
green: "\x1b[42m",
yellow: "\x1b[43m",
blue: "\x1b[44m",
magenta: "\x1b[45m",
cyan: "\x1b[46m",
white: "\x1b[47m",
gray: "\x1b[100m",
crimson: "\x1b[48m"
}
};
Here's an example of how to use it:
console.log(colours.bg.blue, colours.fg.white, "I am a white message with a blue background", colours.reset) ;
// Make sure that you don't forget "colours.reset" at the so that you can reset the console back to it's original colours.
Or you can install some utility modules:
npm install console-info console-warn console-error --save-dev
These modules will show something like the following to the console when you use them:
to color your output You can use examples from there:
https://help.ubuntu.com/community/CustomizingBashPrompt
Also a Gist for nodeJs
For example if you want part of the text in red color, just do console.log with:
"\033[31m this will be red \033[91m and this will be normal"
Based on that I've created "colog" extension for Node.js. You can install it using:
npm install colog
Repo and npm:
https://github.com/dariuszp/colog
Emoji
You can use colors for text as others mentioned in their answers.
But you can use emojis instead! for example, you can use⚠️ for warning messages and 🛑 for error messages.
Or simply use these notebooks as a color:
📕: error message
📙: warning message
📗: ok status message
📘: action message
📓: canceled status message
📔: Or anything you like and want to recognize immediately by color
🎁 Bonus:
This method also helps you to quickly scan and find logs directly in the source code.
for example:
console.log('Bring with ❤️ to you from Mojtaba Hosseini');
Some Linux distributions default emoji font may not be colorful by default and you may want to make them colorful, first.
How to open emoji picker?
mac os: control + command + space
windows: win + .
linux: control + . or control + ;
Reset: "\x1b[0m"
Bright: "\x1b[1m"
Dim: "\x1b[2m"
Underscore: "\x1b[4m"
Blink: "\x1b[5m"
Reverse: "\x1b[7m"
Hidden: "\x1b[8m"
FgBlack: "\x1b[30m"
FgRed: "\x1b[31m"
FgGreen: "\x1b[32m"
FgYellow: "\x1b[33m"
FgBlue: "\x1b[34m"
FgMagenta: "\x1b[35m"
FgCyan: "\x1b[36m"
FgWhite: "\x1b[37m"
FgGray: "\x1b[90m"
BgBlack: "\x1b[40m"
BgRed: "\x1b[41m"
BgGreen: "\x1b[42m"
BgYellow: "\x1b[43m"
BgBlue: "\x1b[44m"
BgMagenta: "\x1b[45m"
BgCyan: "\x1b[46m"
BgWhite: "\x1b[47m"
FgGray: "\x1b[100m"
For example if you want to have a Dim, Red text with Blue background you can do it in Javascript like this:
console.log("\x1b[2m", "\x1b[31m", "\x1b[44m", "Sample Text", "\x1b[0m");
The order of the colors and effects seems to not be that important but always remember to reset the colors and effects at the end.
Per this documentation, you can change the colors based on the data type of the output:
// you'll need the util module
var util = require('util');
// let's look at the defaults:
util.inspect.styles
{ special: 'cyan',
number: 'yellow',
boolean: 'yellow',
undefined: 'grey',
null: 'bold',
string: 'green',
date: 'magenta',
regexp: 'red' }
// what are the predefined colors?
util.inspect.colors
{ bold: [ 1, 22 ],
italic: [ 3, 23 ],
underline: [ 4, 24 ],
inverse: [ 7, 27 ],
white: [ 37, 39 ],
grey: [ 90, 39 ],
black: [ 30, 39 ],
blue: [ 34, 39 ],
cyan: [ 36, 39 ],
green: [ 32, 39 ],
magenta: [ 35, 39 ],
red: [ 31, 39 ],
yellow: [ 33, 39 ] }
These appear to be ANSI SGR escape codes, where the first number is the code to emit before the output, and the second number is the code to emit after. So if we look at the chart of ANSI SGR codes on Wikipedia, you'll see that most of these start with a number 30-37 to set the foreground color, and end in 39 to reset to the default foreground color.
So one thing I don't like is how dark some of these are. Especially dates. Go ahead and try new Date() in the console. Dark magenta on black is really hard to read. Let's change that to a light magenta instead.
// first define a new color
util.inspect.colors.lightmagenta = [95,39];
// now assign it to the output for date types
util.inspect.styles.date = 'lightmagenta';
Now when you try new Date(), the output is much more readable.
If you'd like to set colors automatically when launching node, create a script that launches the repl, like this:
// set your colors however desired
var util = require('util');
util.inspect.colors.lightmagenta = [95,39];
util.inspect.styles.date = 'lightmagenta';
// start the repl
require('repl').start({});
Save this file (for example, init.js), then run node.exe init.js. It will set the colors and launch the node.js command prompt.
(Thanks to loganfsmyth in this answer for the repl idea.)
I found this answer above (https://stackoverflow.com/a/41407246/4808079) very useful, but incomplete. If you only ever wanted to color something once, I guess it'd be fine, but I think sharing it in a runnable functional form is much more applicable to real life use cases.
const Color = {
Reset: "\x1b[0m",
Bright: "\x1b[1m",
Dim: "\x1b[2m",
Underscore: "\x1b[4m",
Blink: "\x1b[5m",
Reverse: "\x1b[7m",
Hidden: "\x1b[8m",
FgBlack: "\x1b[30m",
FgRed: "\x1b[31m",
FgGreen: "\x1b[32m",
FgYellow: "\x1b[33m",
FgBlue: "\x1b[34m",
FgMagenta: "\x1b[35m",
FgCyan: "\x1b[36m",
FgWhite: "\x1b[37m",
FgGray: "\x1b[90m",
BgBlack: "\x1b[40m",
BgRed: "\x1b[41m",
BgGreen: "\x1b[42m",
BgYellow: "\x1b[43m",
BgBlue: "\x1b[44m",
BgMagenta: "\x1b[45m",
BgCyan: "\x1b[46m",
BgWhite: "\x1b[47m"
BgGray: "\x1b[100m",
}
function colorString(color, string) {
return `${color}${string}${Color.Reset}`;
}
function colorLog(color, ...args) {
console.log(...args.map(
(it) => typeof it === "string" ? colorString(color, string) : it
));
}
Use it like this:
colorLog(Color.FgYellow, "Some Yellow text to console log", { someObj: true });
console.log([
colorString(Color.FgRed, "red"),
colorString(Color.FgGreen, "green"),
colorString(Color.FgBlue, "blue"),
].join(", "));
A handy one-liner I wrote for npm scripts that can't have dependencies:
const { r, g, b, w, c, m, y, k } = [
['r', 1], ['g', 2], ['b', 4], ['w', 7],
['c', 6], ['m', 5], ['y', 3], ['k', 0],
].reduce((cols, col) => ({
...cols, [col[0]]: f => `\x1b[3${col[1]}m${f}\x1b[0m`
}), {})
console.log(`${g('I')} love ${r('Italy')}`)
r,g,b,w,c,m,y,k stands for red, green, blue, white, cyan, magenta, yellow and black.
If you want to keep it SIMPLE without using any external module / learn new APIs / hacking the core console functions:
const LCERROR = '\x1b[31m%s\x1b[0m'; //red
const LCWARN = '\x1b[33m%s\x1b[0m'; //yellow
const LCINFO = '\x1b[36m%s\x1b[0m'; //cyan
const LCSUCCESS = '\x1b[32m%s\x1b[0m'; //green
const logger = class {
static error(message, ...optionalParams) { console.error(LCERROR, message, ...optionalParams) }
static warn(message, ...optionalParams) { console.warn(LCWARN, message, ...optionalParams) }
static info(message, ...optionalParams) { console.info(LCINFO, message, ...optionalParams) }
static success(message, ...optionalParams) { console.info(LCSUCCESS, message, ...optionalParams) }
}
// then instead (as presented in the accepted answer)
// console.error(LCERROR, 'Error message in red.');
// you write:
logger.error('Error message in red.');
// or with multiple parameters (only the message will be red):
logger.error('Error message in red.', 1, false, null, {someKey: 'whatever'});
// or use backticks (template literal) instead multiple params:
logger.error(`This will be red as ${foo} and ${bar} too.`);
Now you can use your logger in the same way as you would with console. There's no new API to remember... Normally you would put it into a module (logger.js) and export the class to be able to use it everywhere in your app as const logger = require('./logger');
This library by Sindre Sorhus is the best at the moment:
chalk
Highly performant
Doesn't extend String.prototype
Expressive API
Ability to nest styles
Clean and focused
Auto-detects color support
Actively maintained
Used by 5500+ modules
No libraries no complications just simple:
console.log(red('Error!'));
function red(s) {
return '\033[31m' + s;
}
For a popular alternative to colors that doesn't mess with the built-in methods of the String object, I recommend checking out cli-color.
Includes both colors and chainable styles such as bold, italic, and underline.
For a comparison of various modules in this category, see here.
I overloaded the console methods.
var colors={
Reset: "\x1b[0m",
Red: "\x1b[31m",
Green: "\x1b[32m",
Yellow: "\x1b[33m"
};
var infoLog = console.info;
var logLog = console.log;
var errorLog = console.error;
var warnLog = console.warn;
console.info= function(args)
{
var copyArgs = Array.prototype.slice.call(arguments);
copyArgs.unshift(colors.Green);
copyArgs.push(colors.Reset);
infoLog.apply(null,copyArgs);
};
console.warn= function(args)
{
var copyArgs = Array.prototype.slice.call(arguments);
copyArgs.unshift(colors.Yellow);
copyArgs.push(colors.Reset);
warnLog.apply(null,copyArgs);
};
console.error= function(args)
{
var copyArgs = Array.prototype.slice.call(arguments);
copyArgs.unshift(colors.Red);
copyArgs.push(colors.Reset);
errorLog.apply(null,copyArgs);
};
// examples
console.info("Numeros",1,2,3);
console.warn("pares",2,4,6);
console.error("reiniciandooo");
The output is.
Came across this question, and wanted to use some colors on stdout without any dependencies. This combines some of the other great answers here.
Here's what I've got. (Requires node v4 or greater)
// colors.js
const util = require('util')
function colorize (color, text) {
const codes = util.inspect.colors[color]
return `\x1b[${codes[0]}m${text}\x1b[${codes[1]}m`
}
function colors () {
let returnValue = {}
Object.keys(util.inspect.colors).forEach((color) => {
returnValue[color] = (text) => colorize(color, text)
})
return returnValue
}
module.exports = colors()
Just require the file, then use it like so:
const colors = require('./colors')
console.log(colors.green("I'm green!"))
The predefinied color codes are available here
There are two ways to look at changing colors for a Node.js console today.
One is through general-purpose libraries that can decorate a text string with color tags, which you then output through the standard console.log.
The top libraries for that today:
chalk
colors
cli-color
And the other way - patching the existing console methods. One such library - manakin lets you automatically set standard colors for all your console methods (log, warn, error and info).
One significant difference from the generic color libraries - it can set colors either globally or locally, while keeping consistent syntax and output format for every Node.js console method, which you then use without having to specify the colors, as they are all set automatically.
I had to change the console background color to white because of eye problems, but the font is gray colored and it makes the messages unreadable. How can I change it?
Specifically for your problem, here's the simplest solution:
var con = require('manakin').global;
con.log.color = 30; // Use black color for console.log
It will set black color for every console.log call in your application. See more color codes.
Default colors as used by manakin:
paint-console
Simple colorable log. Support inspect objects and single line update
This package just repaint console.
install
npm install paint-console
usage
require('paint-console');
console.info('console.info();');
console.warn('console.warn();');
console.error('console.error();');
console.log('console.log();');
demo
This somewhat depends on what platform you are on. The most common way
to do this is by printing ANSI escape sequences. For a simple example,
here's some python code from the blender build scripts:
// This is a object for use ANSI escape to color the text in the terminal
const bColors = {
HEADER : '\033[95m',
OKBLUE : '\033[94m',
OKGREEN : '\033[92m',
WARNING : '\033[93m',
FAIL : '\033[91m',
ENDC : '\033[0m',
BOLD : '\033[1m',
UNDERLINE : '\033[4m'
}
To use code like this, you can do something like
console.log(`${bColors.WARNING} My name is sami ${bColors.ENDC}`)
I don't want any dependency for this and only these worked for me on OS X. All other samples from answers here gave me Octal literal errors.
Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"
FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"
FgGray = "\x1b[90m"
BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
BgGray = "\x1b[100m"
source: https://coderwall.com/p/yphywg/printing-colorful-text-in-terminal-when-run-node-js-script
var colorSet = {
Reset: "\x1b[0m",
Red: "\x1b[31m",
Green: "\x1b[32m",
Yellow: "\x1b[33m",
Blue: "\x1b[34m",
Magenta: "\x1b[35m"
};
var funcNames = ["info", "log", "warn", "error"];
var colors = [colorSet.Green, colorSet.Blue, colorSet.Yellow, colorSet.Red];
for (var i = 0; i < funcNames.length; i++) {
let funcName = funcNames[i];
let color = colors[i];
let oldFunc = console[funcName];
console[funcName] = function () {
var args = Array.prototype.slice.call(arguments);
if (args.length) {
args = [color + args[0]].concat(args.slice(1), colorSet.Reset);
}
oldFunc.apply(null, args);
};
}
// Test:
console.info("Info is green.");
console.log("Log is blue.");
console.warn("Warn is orange.");
console.error("Error is red.");
console.info("--------------------");
console.info("Formatting works as well. The number = %d", 123);
logger/index.js
const colors = {
Reset : "\x1b[0m",
Bright : "\x1b[1m",
Dim : "\x1b[2m",
Underscore : "\x1b[4m",
Blink : "\x1b[5m",
Reverse : "\x1b[7m",
Hidden : "\x1b[8m",
FgBlack : "\x1b[30m",
FgRed : "\x1b[31m",
FgGreen : "\x1b[32m",
FgYellow : "\x1b[33m",
FgBlue : "\x1b[34m",
FgMagenta : "\x1b[35m",
FgCyan : "\x1b[36m",
FgWhite : "\x1b[37m",
BgBlack : "\x1b[40m",
BgRed : "\x1b[41m",
BgGreen : "\x1b[42m",
BgYellow : "\x1b[43m",
BgBlue : "\x1b[44m",
BgMagenta : "\x1b[45m",
BgCyan : "\x1b[46m",
BgWhite : "\x1b[47m",
};
module.exports = () => {
Object.keys(colors).forEach(key => {
console['log' + key] = (strg) => {
if(typeof strg === 'object') strg = JSON.stringify(strg, null, 4);
return console.log(colors[key]+strg+'\x1b[0m');
}
});
}
app.js
require('./logger')();
Then use it like:
console.logBgGreen(" grüner Hintergrund ")
Coolors
It's pretty good for use or extend. You can use simply:
var coolors = require('coolors');
console.log(coolors('My cool console log', 'red'));
Or with config:
var coolors = require('coolors');
console.log(coolors('My cool console log', {
text: 'yellow',
background: 'red',
bold: true,
underline: true,
inverse: true,
strikethrough: true
}));
And seems really funny to extend:
var coolors = require('coolors');
function rainbowLog(msg){
var colorsText = coolors.availableStyles().text;
var rainbowColors = colorsText.splice(3);
var lengthRainbowColors = rainbowColors.length;
var msgInLetters = msg.split('');
var rainbowEndText = '';
var i = 0;
msgInLetters.forEach(function(letter){
if(letter != ' '){
if(i === lengthRainbowColors) i = 0;
rainbowEndText += coolors(letter, rainbowColors[i]);
i++;
}else{
rainbowEndText += ' ';
}
});
return rainbowEndText;
}
coolors.addPlugin('rainbow', rainbowLog);
console.log(coolorsExtended('This its a creative example extending core with a cool rainbown style', 'rainbown'));
View Coolors module
I created my own module, StyleMe. I made it so I can do much with little typing. Example:
var StyleMe = require('styleme');
StyleMe.extend() // extend the string prototype
console.log("gre{Hello} blu{world}!".styleMe()) // Logs hello world! with 'hello' being green, and 'world' being blue with '!' being normal.
It can also be nested:
console.log("This is normal red{this is red blu{this is blue} back to red}".styleMe())
Or, if you dont want to extend the string prototype, you can just any of the 3 other options:
console.log(styleme.red("a string"))
console.log("Hello, this is yellow text".yellow().end())
console.log(styleme.style("some text","red,bbl"))
You can also use colorworks.
Usage:
var cw = require('colorworks').create();
console.info(cw.compile('[[red|Red message with a [[yellow|yellow]] word.]]'));
To make life easier, you can also make a function with it.
function say(msg) {
console.info(cw.compile(msg));
}
Now you can do:
say(`[[yellow|Time spent: [[green|${time}]]ms.]]`);
I've made a file in my snippets directory called styles.js, and I think it might help anybody who wants to import a single file.
It's a small modification to the styles.js file of color.js and has helped me a lot.
Here's the file's contents:
// Original: https://github.com/Marak/colors.js/blob/master/lib/styles.js
const styleCodes = {
// Reset all styles.
reset: [0, 0],
// Text styles.
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],
// Foregound classic colours.
fgBlack: [30, 39],
fgRed: [31, 39],
fgGreen: [32, 39],
fgYellow: [33, 39],
fgBlue: [34, 39],
fgMagenta: [35, 39],
fgCyan: [36, 39],
fgWhite: [37, 39],
fgGray: [90, 39],
// Foreground bright colours.
fgBrightRed: [91, 39],
fgBrightGreen: [92, 39],
fgBrightYellow: [93, 39],
fgBrightBlue: [94, 39],
fgBrightMagenta: [95, 39],
fgBrightCyan: [96, 39],
fgBrightWhite: [97, 39],
// Background basic colours.
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
bgGray: [100, 49],
bgGrey: [100, 49],
// Background bright colours.
bgBrightRed: [101, 49],
bgBrightGreen: [102, 49],
bgBrightYellow: [103, 49],
bgBrightBlue: [104, 49],
bgBrightMagenta: [105, 49],
bgBrightCyan: [106, 49],
bgBrightWhite: [107, 49],
};
// This object will contain the string representation for all style codes.
const styles = {};
// Loop over all the style codes and assign them to the `styles` object.
//
// The a `styleCode` in the `styleCodes` object consists of two numbers:
// Index 0: The opening style code (In HTML this can be the opening <b> tag).
// Index 1: The closing style code (In HTML this can be the closing </b> tag).
for (let styleCode of Object.keys(styleCodes)) {
styles[styleCode] = {
open: `\x1B[${styleCodes[styleCode][0]}m`,
close: `\x1B[${styleCodes[styleCode][1]}m`,
};
}
module.exports = styles;
It's actually quite simple to use.
const styles = require("/path/to/styles.js");
// Let's say we've got an error:
const errorOpen = styles.bold.open + styles.bgRed.open + styles.fgWhite.open;
const errorClose = styles.reset.close; // Close everything
console.log(errorOpen, "ERROR", errorClose, ": Missing semicolon at line 9.");
2017:
Simple way, adding time color to the message, you don't need to change your code, use keep your console.log('msg') or console.err('error')
var clc = require("cli-color");
var mapping = {
log: clc.blue,
warn: clc.yellow,
error: clc.red
};
["log", "warn", "error"].forEach(function(method) {
var oldMethod = console[method].bind(console);
console[method] = function() {
oldMethod.apply(
console,
[mapping[method](new Date().toISOString())]
.concat(arguments)
);
};
});
If you are using Windows CMD then go to the terminal Properties/Colors (CMD top left) and then redefine the RGB value of the offensive color. In my case I believe it's the fifth color square from the left, which I changed to (222,222,222). It does not matter if the currently selected radio button shows Screen Text or Screen Background as you just redefine that specific "system" color. Once you changed the color don't forget to select back the preferred color for the background or text before clicking OK.
After the change all these reddish messages from Node (Ember in my case) are clearly visible.
In ubuntu you can simply use color codes:
var sys = require('sys');
process.stdout.write("x1B[31m" + your_message_in_red + "\x1B[0m\r\n");
node-colorify
Provides functions to print texts in color and also to do text formatting such as bold, blink, etc..

Resources