Skip to content
This repository has been archived by the owner on Oct 9, 2020. It is now read-only.

[Bug] "jsl.pause()" doesn't unregister events -> leads to "stacking" line breaks #38

Closed
Sv443 opened this issue Mar 18, 2020 · 1 comment · Fixed by #40
Closed

[Bug] "jsl.pause()" doesn't unregister events -> leads to "stacking" line breaks #38

Sv443 opened this issue Mar 18, 2020 · 1 comment · Fixed by #40
Assignees
Labels
🐛 bug Something isn't working
Milestone

Comments

@Sv443
Copy link
Owner

Sv443 commented Mar 18, 2020

If jsl.pause() is used multiple times in the same process, due to the process.stdin.on("data") event not being unregistered, the callback and line breaks will be called multiple times, increasing by one each time jsl.pause() is used.
This might also result in the wrong callbacks being executed at the wrong time, causing bugs that are horrible to debug.

Example code:

let allFlags = ["nsfw", "religious", "political", "racist", "sexist"];

let flagIteration = idx => {
    if(idx >= allFlags.length)
        return flagIterFinished();
    else
    {
        jsl.pause(`Is this joke ${allFlags[idx]}? (y/N):`).then(key => {
            if(key.toLowerCase() == "y")
                joke["flags"][allFlags[idx]] = true;
            else joke["flags"][allFlags[idx]] = false;

            return flagIteration(++idx);
        }).catch(err => {
            console.error(`Error: ${err}`);
            return process.exit(1);
        });
    }
};

flagIteration(0);

Results in:

image

@Sv443 Sv443 added the 🐛 bug Something isn't working label Mar 18, 2020
@Sv443 Sv443 added this to the v1.9.1 milestone Mar 18, 2020
@Sv443 Sv443 self-assigned this Mar 18, 2020
@Sv443
Copy link
Owner Author

Sv443 commented Mar 18, 2020

This should fix it:

function pause(text = "Press any key to continue...")
{
    if(!process.stdin.isRaw)
        process.stdin.setRawMode(true);

    return new Promise((resolve, reject) => {
        process.stdout.write(`${text} `);
        process.stdin.resume();

        let onData = function(chunk)
        {
            if(/\u0003/gu.test(chunk)) // eslint-disable-line no-control-regex
                process.exit(0);

            process.stdout.write("\n");
            process.stdin.pause();

            process.stdin.removeListener("data", onData);
            return resolve(chunk.toString());
        }

        process.stdin.on("data", onData);

        process.stdin.on("error", err => {
            return reject(err);
        });
    });
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
🐛 bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant