Nodejs shell script works fine in linux but not in

2019-07-26 06:31发布

问题:

I have found a difference in how my node.js shell script works in Windows vs Linux. I have a string of commands that are synchronously executed using the child_process library.

var cmd = `echo 'hello'
echo 'Stack'
echo 'Overflow'`

var exec = require('child_process').execSync;
var options = {
  encoding: 'utf8'
};
console.log(exec(cmd, options));

In Linux

This executes all 3 echo statements and outputs as I expect it to.

hello
Stack
Overflow

In Windows

Whereas in Windows, I don't know if it executes 3 times or not. All I do know is that only the first echo command is outputted.

hello

Why am I seeing this difference and can I fix it so that the Windows script outputs similar to the way it does on Linux?

回答1:

You should use:

var cmd = "echo 'hello' && echo 'Stack' && echo 'Overflow'"

instead of

var cmd = `echo 'hello'
echo 'Stack'
echo 'Overflow'`

I am not quite sure why this works but I have a guess.

&& executes this command only if previous command's errorlevel is 0.

Which means that it treats each line as separate commands. Whereas in your way, it (probably) treats each line as the same command, and for whatever reason this causes it to only output the first line.



回答2:

Could it be that the script was created in linux and therefore it has LF (LineFold) \n line-endings? windows on the other hand expects CRLF (CarrageReturn LineFold) \r\n.

When you change the line-ending in your editor of choice to windows-style line endings, I bet it will work.