Search code examples
sshterminalpm2

Why did my SSH server's colors get eaten when running via PM2?


I wrote a simple SSH server using ssh2 that tries to print colored output when a user connects. Here is the code:

import fs from 'fs';
import {Server} from 'ssh2';
import chalk from 'chalk';

console.log('normal');
console.log(chalk.green('green'));

const server = new Server(
    { hostKeys: [fs.readFileSync('../../DEPLOY/data/https/certificate.pem')] },
    (client) => {
        console.log('connect');
        client.on('error', (error) => {
            console.error(error);
        }).on('authentication', (context) => {
            console.log('authenticated');
            context.accept();
        }).on('ready', () => {
            console.log('ready');
            client.on('session', (accept) => {
                console.log('session');
                const session = accept();
                session.once('shell', (accept) => {
                    console.log('shell');
                    const channel = accept();
                    channel.write('normal\n');
                    channel.write(chalk.green('green\n'));
                });
            });
        }).on('close', () => {
            console.log('closed');
        });
    }
);

server.listen(3333, () => {
    console.log('listening on 3333');
});

I first print out 'normal' without color, then I print out 'green' in green just to test that chalk is working. Then I also send the colored and uncolored text over the ssh channel.

If I start my server using npx ts-node <myfile>, then it works properly on the server side:

server with colors

and on the client side:

client with colors

However, when I try to run the server with PM2, I don't get the colors on the server side:

server with no colors

nor on the client side:

client with no colors

I tried setting DEBUG_COLORS=true and I tried setting FORCE_COLOR=1, but neither of those seemed to do anything.

What is PM2 doing with my colors?


Solution

  • Simply add --color to the args in the ecosystem file, like this:

    module.exports = {
        apps: [
            {
                /* ... */
                args: '--color --myOtherArg',
                /* ... */
            },
        ],
    };
    

    Here's another similar answer and a github issue for reference.