question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

colors not showing up after spawning child process

See original GitHub issue

environment

Edition - Windows 10 Pro Version - 1909 OS build - 18363.535

Using Git Bash

details

so I am creating a library to push code to git using some helpful prompts. Those prompts contains some colors too.

Every thing is working perfectly & colors are showing up as they should until I used a child process (with {stdio: “inherit”}). Child process works perfectly while logging to my stdout.

The actual issue comes after this, no colors are shown & their corresponding codes are displayed now.

check the last line in the above push-code commit control flow. Rather than green color for Successfully commit to git , it is printing its code.

Here is my source-code for debugging (not included the bin entry point since it is not relevant & only tranferring control flow to this file) -

const prompts = require("prompts");
const chalk = require("chalk");
const spawn = require('await-spawn');

/**
 * default commit flow
 * @return {Promise<{}>}
 */
module.exports = async function () {

    // to make sure you wish to commit
    let response = await prompts({
        type: "confirm",
        name: "confirm",
        message: "Sure you wish to commit ?",
    });

    if (response.confirm) {

        const commit = {};

        // select type of commit
        response = await prompts({
            type: "select",
            name: "type",
            message: "Type of commit ?",
            choices: [
                {title: "Improvements", value: "Code Improvements"},
                {title: "Bug Fixes", value: "Bug Fixes"},
                {title: "New Code", value: "New Code"}
            ],
            initial: 0
        });

        commit.type = response.type;

        // ask user for commit message & description
        try {

			// don't worry about message & describe
			// they are working perfectly & returning string
			// not including them to make this code concise
            commit.message = await message();
            commit.describe = await description();


            // running commands
            console.log("\n\n" + chalk.blue("Adding files to git ..."));
            await spawnIO('git', 'add', '.');
            console.log(chalk.green("Successfully added files to git"));

            // committing files
            console.log("\n\n" + chalk.blue("Committing to git ..."));
            await spawnIO('git', 'commit', '-S', '-m', `${commit.type} : ${commit.message}`, '-m', `${commit.describe}`, '--no-verify');
            console.log(chalk.green("Successfully committed to git"));

            return true;

        } catch (e) {
            return Promise.reject(e)
        }

    } else {
        return Promise.reject("Commit cancelled by user")
    }
};

/**
 * spawn a new process with inherited stdio
 * @return {Promise<boolean>}
 */
async function spawnIO(...args) {
    const cmd = args[0];
    args.shift();

    try {
        await spawn(cmd, args, {stdio: 'inherit'});
        return true;
    } catch (e) {
        return Promise.reject("failed to execute the command")
    }
};

note that if I include more flow after the commit step , then no lines are showing the color anymore after this (only their corresponding codes)

weird thing

if the child-process doesn’t write to stdout then then next line properly show the the chalk colors like in git add . command in above code & image.

more weird thing

everything is completely working perfectly when using VS-code inbuilt terminal with bash support.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
everhardtcommented, Oct 13, 2020

I got it working by adding FORCE_COLOR ‘1’ to the environment variables of the forked process:

import { fork } from 'child_process';

const process = fork(
  this.processPath,
  {
    env: { ...process.env, FORCE_COLOR: '1' },
  },
);
1reaction
Qix-commented, Oct 13, 2020

There are two issues here, neither of which are chalk’s fault:

  • The issue in the OP describes a case where the terminal emulator is not honoring escape sequences. Git bash is notorious for this; I recommend using the Windows Terminal downloadable from the windows store.
  • The issue some of the responses are facing are codes not being emitted at all, which is due to the stdio not being inherited properly.

Chalk doesn’t concern itself with how stdio is linked up so this is an issue to investigate yourself - we can’t provide support here since it’s not directly related to chalk.

Read more comments on GitHub >

github_iconTop Results From Across the Web

node.js - preserve color when executing child_process.spawn
There are new 'stdio' option for child_process.spawn(). Try following: spawn("path to executable", ... If the sub-process you're running uses supports-color ...
Read more >
Suspicious Browser Child Process - Elastic
Suspicious Browser Child Processedit. Identifies the execution of a suspicious browser child process. Adversaries may gain access to a system through a user ......
Read more >
Is there a way to preserve text color codes on piped stdout ...
Is there a way to preserve text color codes on piped stdout subprocesses? ... I'm using tokio 's Command type to spawn processes/run...
Read more >
About Spawn Processes - Help Home - e-Builder
E-Builder Administrators and those actors in the spawn process step will be able to ... While creating a child (spawned) process, ensure the...
Read more >
Using SPAWN and Pipes - L3HarrisGeospatial.com
Example: Communicating with a Child Process via an Operating System Pipe. The C program shown in the following example (test_pipe.c) accepts floating- point ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found