[Bug] "jsl.pause()" doesn't unregister events -> leads to "stacking" line breaks
Closed this issue · 1 comments
Sv443 commented
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:
Sv443 commented
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);
});
});
}