Search code examples
node.jsexpressstdio

node.js, express server, and i need to send my stderr that i see in console to my webpage too


i have a nodejs express server in glitch website like this:

const express = require("express");
const app = express();
const port = 3000;

const server = app.listen(port, () =>
    console.log(`app listening on port ${port}!`)
);

and a socket.io connection:

const io = require("socket.io")(server);

and some codes communicating between my clients and service going on. something like this:

function input(cmd) {
    //cmd is the recieving data recived from socket
    if (cmd != 'exit') {
        try {
            eval(cmd);
        } catch (e) {
            console.log(e);
        }
    } else {
        process.exit(0)
    }
}

now i need to send all my stdout/stderr messages through a socket back to one of my webpages. my leads so far was using process.stderr/out/in and its .on('data'... event, atleast thats how i'm hoping to be the case. but i didnt manage to make it work. any idea how i can make it work?

(btw i know that using things like that eval() and the way im using it is a bad idea but thats just what i need here, thank you xD)


Solution

  • finally found the solution, here it is anyway if others may come to same problem:

    const originalStdoutWrite = process.stdout.write;
    const originalStderrWrite = process.stderr.write;
    
    process.stdout.write = (chunk, encoding, callback) => {
        socket.emit('cli_out', chunk.toString());
        originalStdoutWrite.apply(process.stdout, [chunk, encoding, callback]);
    };
    
    process.stderr.write = (chunk, encoding, callback) => {
        socket.emit('cli_out', chunk.toString());
        originalStderrWrite.apply(process.stderr, [chunk, encoding, callback]);
    };