2

I have been seeing in some questions on Stack Overflow that there is examples, example code or snippets. Such as the one below:

console.log(1, 2, 3)

By running the code snippet above you'll see something like this:

console.log output

I am currently working with something in node.js that also requires to fetch the output from console.logs. I find it fascinating that Stack Overflow is able to do this, whilst I don't even have a single clue how they did this.

I would be very thankful if someone could send me a link to where I can read and learn about how to fetch data form the console API.

Cheers,
Richard

P.S. If someone could edit this post to display the image, I'd be very thankful.

Edit
The project that I'm working on is an Electron app. It uses both the node.js process and the Electron BrowserWindow.

It uses a logger that I'm working on wich needs to fetch data from console.log

Some of the use cases might look like this:

console.log('%d is cool', User.firstName)
// => "Jason is cool"

or

console.log('User ID:', User._id)
// => A5FFE

or

console.log('%cUser connected!', 'color: #00FF00')
// => User connected!
// In green text.
0

2 Answers 2

2

You can overwrite window.console.log with your own function to achieve such an effect. For example:

const oldConsoleLog = console.log.bind(console);
console.log = (...params) => {
  const textToDisplay = params.map(param =>
    typeof param === 'object'
    ? JSON.stringify(param)
    : param
  );
  document.body.appendChild(document.createElement('div'))
    .textContent = textToDisplay;
  oldConsoleLog(...params);
};

console.log('foo');
console.log('bar baz');
console.log({ prop: 'value' });
.as-console-wrapper {
  height: 60%
}

Sign up to request clarification or add additional context in comments.

4 Comments

But then again, doing something like console.log(1, 2, 3) would only output 1.
See edit, you can use ... to turn all arguments into an array
Then doing something like console.log('%d is cool', 'Jason') would work as well?
@iHack To replicate all of its functionality you'll have to code to replace %s with the other parameters.
1

In nodejs, console.log just formats the data you pass to it and then writes it to process.stdout which is a stream that goes to your commandline window. To intercept that, you can just listen for events on that stream:

process.stdout.on("data", chunk => {
  // Do what you wanna do
});

4 Comments

Though what if the code is executed in for example nw.js or Electron?
@iHack I am currently working with something in node.js ... I just answered the question you asked ...
What I'm making needs to be supported in Electron as well, since my app is going to use a special logger both inside of the Electron Browser and the node.js process. Sorry, i'll edit my question.
Edited my question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.