Ran Shorowitz
Ran Shorowitz

Reputation: 305

Replace console.log(), how to input multiple arguments? (NodeJS)

I want to make a new function to "replace" console.log(). Basically a print() function that lets you add a timestamp at the beginning of the text and also change the colors of the timestamp, followed by the text you want to print.

Example:

colors = require('colors')

function debug_print(str) {
    console.log(new String(Date().getTime().brightBlue + ": " + str)
}

It works, however it doesn't have the feature where you can place multiple arguments into the function call, or so you can print out an object the way console.log does:

myObject = {"hello": "hey"}
console.log("myObject", myObject); // <-- Works, prints out "myObject {'hello' : 'hey'}"
debug_print("myObject", myObject); // <-- Doesn't work

How do I change my function to both allow multiple arguments and also print out objects the same way console.log does, all in one print line?

Upvotes: 0

Views: 590

Answers (2)

Seti
Seti

Reputation: 2314

You can use spread operator when defining function arguments. You should not use arguments itself (unless you really know what you are doing by that).

function debug_print(...msg) {
    console.log('whatever: ', ...msg);
}

Upvotes: 1

Cubix48
Cubix48

Reputation: 2681

You can use arguments object to do so.

In Javascript, arguments is a local JavaScript object variable that is available in all non-arrow functions.

It is an Array-like object, containing all the arguments passed.

function my_function() {
    // convert Arguments to a normal Array
    var args = Array.from(arguments);
    
    console.log.apply(console, args)
}

my_function(1, 2, "custom text") // 1, 2, "custom text"

As you want to add a text at the beginning of the message, you can simply add an element at the beginning of the Array

args.unshift(timestamp + ": ");

Upvotes: 1

Related Questions