How to force UTF-8 in node js with exec process?

Solution 1:

When you use dir in the command prompt the renderer knows which character encoding stdout is using, decodes the text bytes and renders the characters with the selected font.

When you exec a command, node does not know which character encoding stdout is using, so you tell it. The problem is you are telling it the wrong thing. To see which character encoding it is, go chcp. But, out-of-the-box, node only supports some of the dozens of characters encodings.

The solution is to tell the command prompt to use one they have in common. Since you are getting paths from the filesystem and the filesystem (NTFS) uses the Unicode character set for paths, UTF-8 is a great choice.

So, this should work:

exec('@chcp 65001 >nul & dir', {encoding: "UTF-8"}, 
    (err, stdout, stderr) => console.log(stdout));

But, the chcp command has a delayed effect and isn't applied to the dir command. Here is one way of working around that:

exec('@chcp 65001 >nul & cmd /d/s/c dir', {encoding: "UTF-8"}, 
    (err, stdout, stderr) => console.log(stdout));

Running a batch file might be a simpler way to get two separate commands to run with sequential effect but that would require setup and clean up.