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!
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With