wrong encoding when using child_process spawn or exec under Windows
I managed to fix it by adding cmd /c chcp 65001>nul &&
(this command sets cmd's console output to utf-8) at start of my exec command, so your would look like cmd /c chcp 65001>nul && dir
, it should work.
If you write cross-platform can use process.platform
, to determine when you need that, something like that:
var cmd = "";
if (process.platform === "win32") {
cmd += "cmd /c chcp 65001>nul && ";
};
cmd += "dir";
child = exec(cmd, //...
- Even though
dir
command is not "cross-platform".
From http://www.nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
There is a second optional argument to specify several options. The default options are
{ encoding: 'utf8',
timeout: 0,
maxBuffer: 200*1024,
killSignal: 'SIGTERM',
cwd: null,
env: null }
That is Node defaults to utf8, while Windows has different code pages for different language version.