I'm writing JavaScript expressions to be used in specialized geospatial software.
In the geospatial software, only console()
is valid, not console.log()
.
As I'm working, I'm debugging my geospatial scripts in VS Code using Node.JS (since the geospatial software doesn't have linting functionality, etc.).
It's my understanding that Node.js uses console.log()
syntax, not console()
.
Therefore, when moving the script back and forth between the two programs, I need to do a find and replace to switch from console()
to console.log()
(and vice versa). This is becoming tedious.
Question:
In VS Code / Node.js, is there a way to use console()
instead of console.log()
? That would make things a lot easier when developing my scripts. I'd be able to have a standard script that works in both programs.
I'm a novice, so layman's terms would be appreciated.
CodePudding user response:
In VS Code / Node.js, is there a way to use
console()
instead ofconsole.log()
?
I can't think of a way to do that that wouldn't potentially blow up code in other modules that you may be using, since it would require reassigning the console
global, and that's...global. (I have included one possible option below, but...I don't like it.)
But even if you can find a way to do that, I wouldn't. Instead, at the top of the script, I'd have something like:
const log = typeof console === "function" ? console : console.log;
...and then use log
(or whatever name you want to use) throughout the script. It'll refer to the appropriate function.
Here's something that might not blow up other code:
console = Object.assign(console.log, console);
That replaces console
with console.log
, but also puts all of the console
properties (well, the own enumerable ones anyway) on the function as properties, so both console
and console.log
(and console.error
, etc.) work. But there's no guarantee that code in an unsuspecting module doesn't do if (typeof console === "object")
to decide whether it can use console
, and that would fail because typeof
would return "function"
for it instead.
So again: I'd use the first solution above: A standalone log
function.