Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readline-sync doesn't use right encoding on windows

I'm using readline-sync to ask users of my noedejs commandline app for some information.
In my linux terminal, everything works fine with german umlauts (öäü) but when reading input on a windows shell (either powershell or cmd) it butchers my input despite having set the encoding to utf8:

var rls = require('readline-sync');
// set encoding for rls:
rls.setDefaultOptions({encoding: 'utf8'});

...

var test = rls.question("Input name: ");
console.log("Created: " + test);

Output on windows:

PS > tim test
Input name: töst
Created: t�st

It's also pretty interesting that parameters I pass to my app via commandline args will have the right characters.

Is this a bug? How can I fix it?

like image 704
wullxz Avatar asked Nov 08 '22 21:11

wullxz


1 Answers

I could not find any way of getting this module to read accents from a Windows terminal correctly. But I noticied that the default module readline does not have this type of problem.

So I made this workaround for the method question:

const readline = require('readline');

const question = question => {
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    return new Promise(resolve => {
        rl.question(question, answer => {
            rl.close();
            return resolve(answer);
        });
    });
};

async function main() {
    const answer = await question('Enter your text with accents: ');
    console.log(answer);
}

main().catch(console.error);

For another methods like keyInSelect you can use this approach too.

like image 154
Giancarl021 Avatar answered Nov 14 '22 22:11

Giancarl021