1

I am new to node js. I have written a script that spawns 5 child process and captures log from them, As of now the log looks like mess.

Screen shot of current output

But i want to display the output in a cleaner format, like each line gets reused and data gets loged next to the process id. something like this: enter image description here

below is my code:

var state = "node stealth.js ";
var exec = require('child_process').exec;


workers = 5

  

p_list = [];

for (var i = 0; i < workers; i++) {
    (function(i){
        var child = exec(state+'user'+i);
        console.log('started Worker '+i)
        // Add the child process to the list for tracking
        p_list.push({process:child, content:""});

        // Listen for any response:
        child.stdout.on('data', function (data) {

            console.log(child.pid, data);
            p_list[i].content += data;
            process.stdout.cursorTo(i);
            process.stdout.clearLine();
            process.stdout.write(child.pid+data);
            process.stdout.write("\n"); // end the line
            
        });

        // Listen for any errors:
        child.stderr.on('data', function (data) {
            console.log(child.pid, data);
            p_list[i].content += data;
        }); 

        // Listen if the process closed
        child.on('close', function(exit_code) {
            console.log('Closed before stop: Closing code: ', exit_code);
        });
    })(i)
}
Max Ahmed
  • 135
  • 1
  • 8

2 Answers2

1

You are looking for VT100 Terminal Control Escape Sequences. These sequences allow to move the cursor around or color the text.

Example

console.log('Line 1');
console.log('Line 2');
console.log('\x1B[1AAgain line 2');

The \x1B[1A sequence at the start moves the cursor one line up and therefore the text after it overwrites the previous text. The result looks like this:

Line 1
Again line 2

For more sequences, check out the part of the page about cursor movement.

Thomas Dondorf
  • 23,416
  • 6
  • 84
  • 105
0

Finally i figured out a solution. Since i need to gather data from different processes and display in a neat way, i started using pm2 process manager, it does a lot more than just console log from processes. for anyone facing same problem please check out this node package

Max Ahmed
  • 135
  • 1
  • 8