3

I made a script in NodeJS with multiple conditions. I want to export/print the console.log to a webpage using NodeJS Server.

function myfunction() { app('Some text', 'ALERT!', function(err, remaining) { if (err) throw err; console.log('Some text.'); 

Is this possible? I've searched everywhere.

Thanks a lot!

3
  • Why do you want to print logs from server to a webpage in client side? Commented Jul 2, 2017 at 19:06
  • Because I want to use them in PRTG (monitoring tool) Commented Jul 2, 2017 at 19:08
  • Try using sockets for these kind of things. Commented Jul 2, 2017 at 19:11

1 Answer 1

5

In order to export/print the console.log(...) result to web page, you can override console.log and make it emit message before it is printed in server console. Then the message will be emitted to browser using Web Socket and printed/used in page.

Example code is listed below.

Server side:

var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var port = process.env.PORT || 3000; var events = require('events'); var eventEmitter = new events.EventEmitter(); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); eventEmitter.on('logging', function(message) { io.emit('log_message', message); }); http.listen(port, function(){ console.log('listening on *:' + port); }); // Override console.log var originConsoleLog = console.log; console.log = function(data) { eventEmitter.emit('logging', data); originConsoleLog(data); }; // code for test. setInterval(function() { console.log('X: ' + Math.random()); }, 2000); 

Browser side:

<!doctype html> <html> <head> <title>Example</title> </head> <body> <ul id="messages"></ul> <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> <script src="https://code.jquery.com/jquery-1.11.1.js"></script> <script> $(function () { var socket = io(); socket.on('log_message', function(msg){ $('#messages').append($('<li>').text(msg)); }); }); </script> </body> </html> 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the example! When I use the script I will get the following error: (node) warning: possible EventEmitter memory leak detected. 11 logging listeners added. Use emitter.setMaxListeners() to increase limit.
@user3130478 This is because a new logging event listener is added each time when there is an io connection. I've edited the code in answer and leave only one logging event listener. Please note this will make console.log(...) statement broadcast message to all client browsers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.