Nodejs shell 脚本在 linux 中运行良好,但在 Windows 中不起作用.为什么它不会执行多个命令 [英] Nodejs shell script works fine in linux but not in Windows. Why won't it execute more than one command

查看:32
本文介绍了Nodejs shell 脚本在 linux 中运行良好,但在 Windows 中不起作用.为什么它不会执行多个命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现我的 node.js shell 脚本在 Windows 和 Linux 中的工作方式有所不同.我有一串使用 child_process 库同步执行的命令.

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));

在 Linux 中

这会按照我的预期执行所有 3 个 echo 语句和输出.

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

hello
Stack
Overflow

在 Windows 中

而在 Windows 中,我不知道它是否执行了 3 次.我所知道的是只输出第一个 echo 命令.

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

<小时>

为什么我会看到这种差异,我是否可以修复它,以便 Windows 脚本输出类似于它在 Linux 上的输出方式?


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?

推荐答案

你应该使用:

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

代替

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

我不太确定为什么会这样,但我有一个猜测.

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

&& 仅当前一个命令的错误级别为 0 时才执行此命令.

&& 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.

这篇关于Nodejs shell 脚本在 linux 中运行良好,但在 Windows 中不起作用.为什么它不会执行多个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆