简体   繁体   中英

nodejs exec command fails for some windows commands with no clear error message

I have an editor in my program and dynamically write commands and execute them. I want to move all files and folders inside myPublish directory to current directory by child_process exec. I use robocopy command in windows. when I test robocopy in cmd, it works correctly:

robocopy /s .\myPublish .\ /move

but in program, nodejs gives an unclear error message that just says: "Command failed: robocopy /s .\\myPublish .\\ /move\\n"

robocopy 命令失败

I've just hit this issue also. While most console applications should return an exit code of zero when there's no errors, robocopy has a series of custom exit codes. This makes Node think that there's been an error during execution, when there may not have been.

As per here , Robocopy has the following exit code bits that make up the exit code:

0×10 Serious error. Robocopy did not copy any files. This is either a usage error or an error due to insufficient access privileges on the source or destination directories.

0×08 Some files or directories could not be copied (copy errors occurred and the retry limit was exceeded). Check these errors further.

0×04 Some Mismatched files or directories were detected. Examine the output log. Housekeeping is probably necessary.

0×02 Some Extra files or directories were detected. Examine the output log. Some housekeeping may be needed.

0×01 One or more files were copied successfully (that is, new files have arrived).

0×00 No errors occurred, and no copying was done. The source and destination directory trees are completely synchronized.

To fix this, you need to catch the error and inspect the error code:

const cp = require('child_process');
try { 
    cp.execSync('robocopy ...'); 
} catch (err) { 
    console.log(err.status);             // get the return code
    console.log(err.output.toString());  // get robocopy's full output
}

I think you would generally consider a code greater than 8 to be a more serious error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM