Node.js console.log vs console.info - javascript

What is the benefit of using console.log vs console.info?
Or any of the other console commands for that matter?
console.info("info");
console.error("error");
console.warn("warn");
vs
console.log("log");
I thought it might change the color of the output or concatenate some sort of label, but they seem to all do the same thing. And according to the documentation here:
https://nodejs.org/api/console.html#console_console_info_data
they seem to all do the same as console.log

According to the documentation that you linked to, console.error and console.warn outputs to stderr. The others output to stdout.
If you are doing piping or redirection from node.js the difference is important.
There is a lot of JavaScript written to run in both the browser and Node.js. Having node implement the full console allows for greater code cross-compatibility.
In most browsers, not only do these log in different colors, but you can also filter to see specific messages.
console.info("info");
console.error("error");
console.warn("warn");
console.log("log");

While console.log and console.info might seem the same, with only mere coloring differences (in most browsers), you can take advantage of having these differently named functions.
For example, you can configure a linter like eslint to produce a warning message whenever console.log is used but no warnings for console.info. Now you can use console.log for temporary development/debug logging and console.info for information that end users might need. The linter warnings will remind or even force you to removed the temporary console.log calls before commits code or publishing release builds.

console.log() is shorter than console.info()
They're the same thing, and that's the only advantage.

According to the docs it's pretty clear.
console.info([data], [...])#
Same as console.log.
console.error([data], [...])#
Same as console.log but prints to stderr.
console.warn([data], [...])#
Same as console.error.
This means there is no benefit or downside. info == log, and warn == error. Unless you want to print to stderr, info and or log will work.

Visually, No difference actually among console.log , console.info , console.warn , as well as console.error regarding the server side(terminal).
However, there are lightweight modules that add blue, orange and red colors for console.info , console.warn , as well as console.error respectively . By that, console API behaves like client-side.
npm i console-info console-warn console-error --save-dev;

One more detail in addition to the accepted answer: In Chrome and FireFox, console.info log lines are prefixed with a little i icon while console.log lines are not. warn and error lines are prefixed with a little triangle and x, respectively.

stdin
A readable stream for reading input from the user.
stdout
A writable stream, either synchronously or asynchronously.
stderr
A blocking synchronous writable stream intended for error messages.
The stdout or non-blocking functions are: console.log, console.info, util.puts, util.print and Stderr.
The blocking functons are: console.warn, console.error, util.debug and process.stdin (a readable stream for getting user input).

It has been established that log and info are basically the same thing, but I'm not sure that completely answers the question:
What is the benefit of using console.log vs console.info?
One benefit, apart from what has already been mentioned, is you can use each for a different purpose. For example, you might use console.log just for quick debugging and spitting things out to the console, while you might use console.info for permanent messages you want to output to the console in your code, such as information on the current app status. Then when you have a situation where a random object is printed in your console and you realize you've left a log statement in there somewhere by accident, you can do a global search for 'console.log' and delete every instance and have confidence you didn't delete anything important that you meant to leave in there.

I have seen where console.log is for temporarily logging of state information for debugging.
console.info is a more permanent thing - such as saying what port something is running on, and something you wouldn't cut out after you are done debugging.
This makes it easy to clean up your code for committing it. You can even have your linter have a rule to prevent console.log from being committed.

There is a difference for React devs. It comes from an issue in the react devtool extension and at least affects Create-React-App users, not sure if it's all web pack.
Issue is mentioned here:
react devtools console.log() from react_devtools_backend.js:4049
but the jist is:
console.log will always report its source as
react_devtools_backend.js:4049
wheres console.info will have the actual filename and line number you're logging from.

The different logging levels let you manage the noise level in your console: In both the Firefox (I'm using 78 right now) and Chrome (84) devtools, the js console lets you choose what "debug level" of output you want to see. FF lets you toggle the visibility of console.error, .warn, .log, .info, and .debug messages by clicking individual buttons for each (that show you how many were suppressed, when "off"), whereas Chrome has a dropdown with checkmarks next to the items (.info and .log are controlled by the "Info" one, and .debug by "Verbose"). The Chrome dropdown label ("All levels" or whatever you set) turns red if output was suppressed.

Related

IE11 Debugging Capabilities

When debugging JavaScript I make heavy use of the console to evaluate individual lines of code, to retrieve instance values to test in 3rd party software (i.e. when building SOAP requests)
Now I've got IE11, it looks like the code I type into the debugger is executed (I can open alert boxes etc..) however the results are not printed in the console. Does this mean I now have to surround everything I type into the console with console.log(JSON.stringify( /* ..expression.. */, null, 4 )) statements?
Is there an easier way to return to the IE10 console behavior?
Answered by #MrAnonymous, please direct all (well deserved) praise to the comments above.
As noted above, this is an issue with the Debugger tools themselves and can be rectified by reloading the tools.

Getting more information from “SyntaxError: Parse error” message in PhantomJS/CasperJS

I have a long CasperJS script. When I run it I get:
phantomjs file.js
SyntaxError: Parse error
Is there a way to get some more information about the error.
At least a line number? or any hint at all?
Try run the file.js with node, so for your example:
node file.js
It's not possible to determine this in PhantomJS itself. The documentation on phantom.onError says:
This is the closest it gets to having a global error handler in PhantomJS
And this doesn't catch the syntax error. If you try to run it with the --debug=true option, you will see a lot of debug messages, but the final error has still the same amount of information.
Another thing that I tried was to use a second PhantomJS script which reads the original script and tries to eval it. The phantom.onError event is triggered in this case, but the trace argument is empty.
The good thing is that PhantomJS/CasperJS scripts are just JavaScript, so you can paste them to http://jslint.com/ or run a dedicated jslinter on them to see where the problem lies. There are some options that you have to mark on the site or otherwise you will get a lot of errors:
add phantom to the global variables box,
enable node.js mode and
tolerate "everything" (or those things that you actually want to tolerate)
I spent a whole 8hrs on this to find a trick for this problem. The trick is to run "phantomjs" and type 'require "path_to_js_file"'. I used 2.1.1 version of phantomjs. Likely 2.2 also works.
Then there will be a stack trace that shows which line is the offender. You won't see this in testem output.
In my case, if you define a property twice for an object, it will work for chrome, firefox etc, but not phantomjs. Lint might help but there are >5K lint errors for the project I work on and it is practically impossible to see what's wrong. Also the particular problem is likely hidden under the same bucket of "javascript strict mode violation". Nodejs didn't complain this either.

Difference between console.log enabled verification

I have seen jquery-ui-1.8.11.js verify console.log functionality by doing
if (this.debug)
console.log()
I have also seen people define an anonymous function that is a no-op for browsers with no console logging like IE7.
if(typeof console === "undefined") {
console = { log: function() { } };
}
Is there a technical difference or are both functionally equivalent?
In the first example you've given, this.debug will be a reference to a debug variable in the jQueryUI code. This debug variable will have been set elsewhere, possibly by checking whether console is defined, but also possibly with other settings.
In any case, the first example is specific to the application; if you want to do a generic check to see whether the console is available, you'll need to use the second technique. You don't have to define an empty console object as per the example, but doing it that way does mean that you won't have to do the if() condition every time you want to call console.log().
Having said all of that, I would counsel you strongly to avoid putting any code into production which contains calls to the console. The console should only be used for debugging purposes while you are working on the code. It should not be necessary in final release, and doing so can be a sign that either your code is unstable or you're unconfident of it, neither of which is a good sign if you're releasing the code for live use.
(libraries such as jQueryUI are an exception to this rule, as they need to provide functionality for developers to do debugging while writing code using their library)
Both of those do something else. The first code suppresses logging messages unless a flag is set. The people who develop jQuery UI need logging when working on it, and turn it on. But people using the library don't want to have their console cluttered by log messages from libraries, so it's off by default. It lets you turn off logging even when the browser supports it – that regular users on IE7 don't get script errors is a (possibly intended) side effect.
The second code defines a dummy console.log(), so you can call the method without checking if it exists everywhere. It will not suppress logging on browsers where it's supported.
The second of the two is standalone, not relying on jQuery. In my opinion, that makes it better.

Getting all info on a Javascript variable

I'm not a JavaScript Wizard by a long shot. But I am a web-developer and so I need to know my way around it at least a bit.
Something I'll often do is simply alert a variable to see what it is.
However, the problem is that I'll often get a result like: "object HTMLInputElement". To me this means little to nothing. Sure I can look it up, but I need to alert children() of children() of children(), etc...
I've tried walking through the JavaScript with Firebug, but for some reason this is very slow. Firefox hangs when I start a debug session, for every single debug session and I don't know why.
So, I want to inform if there is a way to get detailed info on variables some other way. Or a system I can use to work with to make things easier.
I find the developer tools in Chrome work quite well, giving a good amount of detail on demand (usually just hovering the mouse over the variable in the script tab; if that variable is a structured object, a little tree control appears and you can drill down). But then, I don't have your Firebug issue either (or at least, not often anymore).
Debugging with alert is very time-wasteful and, as you've found, frustrating; if at all possible I'd look at using a real debugger (like Chrome's Dev Tools; I've also heard good things about Opera's).
This should help:
http://www.openjs.com/scripts/others/dump_function_php_print_r.php
The easiest way to inspect a javascript variable is with a debugger. If Firebug is not working out for you try using Google Chrome, it has an inspector built in.
Btw - not sure what you mean by "start a debug session". If you have firebug installed, you should simply be able to click on the firebug icon on the bottom right of your browser. Go to the script tab, and select from the drop down whatever js file you want, stick in a break point (just left-click on the margin) and refresh the page. I've never had a problem with Firebug, it's always worked extremely well. I strongly advise figuring out whatever your issue with it is, it will make your life a million times easier.
Using any of the browser dev tools, including IE9, you can use console.log to get the variable output on the console. What information this gives you will vary by browser, but with Firebug it allows you to explore the variable in the DOM inspector tab, with full access to all properties and functions (you can even copy the content of a function to paste elsewhere).
For instance:
var foo = {};
// Do lots of stuff with foo
if (typeof(console) !== "undefined" && console.log) { // prevent errors when console not open, ideally all console calls should be removed before going into production
console.log(foo);
}
This has the advantage that it doesn't require any break points, so no slow step-debugging. It won't solve everything though, you'll often still need the debugger.

Javascript best practice: handling Firebug-specific code

Firebug is certainly a wonderful tool for javascript debugging; I use console.log() extensively.
I wanted to know if I can leave the Firebug-specific code in production.
What's the best practice? Commenting the debug code?
If you leave console.log() calls in your production code, then people visiting the site using Internet Explorer will have JavaScript errors. If those people have extra debugging tools configured, then they will see nasty dialog boxes or popups.
A quick search revealed this thread discussing methods to detect if the Firebug console exists: http://www.nabble.com/Re:-detect-firebug-existance-td19610337.html
been bitten by this before. Ideally all the console.log statements need to be removed before production, but this is error prone and developers invariably forget or only test in FF + Firebug.
A possible solution is to create a dummy console object if one isn't already defined.
if( typeof window.console == 'undefined'){
window.console = {
log:function(){}
};
}
One word of caution: It used to be the case for Safari on 10.4 that any call to console.log would throw a security exception as the console object is a reserved object used in the Mac OS Dashboard widgets. Not sure this is the case anymore, will check tonight.
Personally I modified my compressor a while ago to strip out console references pre-compress. A few minutes adding a regex there saves a lifetime of hassle.
Just thought I would add a really good tip for any js debugging.... use the keyword "debugger", and its like a breakpoint in the code, firebug detects it also MSIE (if you have visual studio) detects it and as I say its a breakpoint.
Not many people seem to know about this but I have found it invaluble... also if there isnt a debugger installed on the machine that is running the code, nothing happens and the code goes through fine. Although I wouldn't advise leaving them in there.
I have had many a headache caused by this.
I use console.log() a lot, and until recently, found that it would cause the entire JS code to fail in versions of FF not using firebug.
I usually run a find before going live, and commenting it out.
D
Some compressors will strip out any line prefixed by ;;; (which is a legal sequence to have, being three empty statements.) This way you're not strictly limited to console references (i.e. you could do some calculations and then console.log() the result at the end, and the compressor can strip all of them out.) I use JavaScript::Minifier for this.
I use this in OOP Javascript, making my own wrapper for log that checks that firebug exists:
myclass.prototype.log = function()
{
if( typeof window.console != 'undefined' )
{
console.log.apply( null, arguments );
}
}
Just call:
this.log( arg1, arg2, ...)
Just a reminder that IE Dev Tool does not support apply() on console.log.
Calling console.log.apply() will raise exception in IE8 when dev tool is active.
You can try JavaScript Debug, it is s simple wrapper for console.log
http://benalman.com/projects/javascript-debug-console-log/

Categories

Resources