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.
iHack
  • 31
  • 5

2 Answers2

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%
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
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
});
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Though what if the code is executed in for example nw.js or Electron? – iHack Jun 02 '18 at 22:56
  • @iHack `I am currently working with something in node.js ` ... I just answered the question you asked ... – Jonas Wilms Jun 02 '18 at 22:57
  • 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. – iHack Jun 02 '18 at 23:00
  • Edited my question. – iHack Jun 02 '18 at 23:07