node.js - Windows 上 npm run 脚本中 shell 脚本的退出状态

标签 node.js windows bash npm

我有一个非常简单的 shell 脚本,test.sh

#!/usr/bin/env bash

exit 1

我从 package.json 中的 test 运行脚本调用此函数

"scripts": {
  "test": "test.sh && echo \"unexpected output\""
},

运行npm test我得到这个:

$ npm test

> testtest@1.0.0 test C:\Users\[path]\testtest
> test.sh && echo "unexpected output"

"unexpected output"

npm 似乎并不关心 test.sh 的非零退出代码。我没想到会看到“意外的输出”。

"test" 命令执行的其中一个步骤(本例中为 test.sh)因错误退出时,如何停止执行该命令?

在我的 package.json 中:"test": "test.sh && echo $?",
这是输出:

$ npm test

> testtest@1.0.0 test C:\Users\[path]\testtest
> test.sh && echo $?

$?

这样:"test": "test.sh && echo\"$?\"",
我明白了:

$ npm test

> testtest@1.0.0 test C:\Users\[path]\testtest
> test.sh && echo "$?"

"$?"

作为健全性检查,我在 test.sh 退出后添加了一个回显。幸好它没有打印:)

#!/usr/bin/env bash

exit 1

echo "This should not print"

“这不应该打印”文本永远不会出现在我的控制台中。

实际上,在 exit 1 之前添加 echo 也不会在我的 GitBash 控制台上打印任何内容。相反,它会打印到 npm 启动的临时 cmd 窗口。所以我猜测退出状态在该 cmd session 中丢失了。

最佳答案

这对我有用:

"scripts": {
  "test": "bash test.sh && echo \"unexpected output\""
},

使用附加的“bash”,脚本将在当前的 Git Bash 中运行。不打印“意外输出”。 如果我省略“bash”,则会打开一个新的 Bash 窗口,并且我还会得到“意外的输出”。

$ npm test

> npm2@1.0.0 test D:\Martin\dev\npm-test\npm2
> bash test.sh && echo "unexpected output"

Hi from script! Next: exit 1
npm ERR! Test failed.  See above for more details.

顺便说一句,如果您正在开发跨平台 Node.js 项目,最好避免使用 Bash/Cmd/Powershell 脚本。只需使用 Node.js 脚本即可,无需安装其他工具。

关于node.js - Windows 上 npm run 脚本中 shell 脚本的退出状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48387948/

相关文章:

node.js - 使用 NodeJS 为 MongoDB 增加值(value)

node.js - Angular 通用集 404 状态代码不起作用

windows - 获取在 Bat 文件中运行的 exe 的进程 ID

bash - 我可以使用子命令运行 watch 吗?

javascript - 从 Node 到浏览器,提供和播放 wav 音频文件的不同方式的优缺点

javascript - 在生产中使用 "coffee"而不是 "node"命令

c++ - 在 Qt C++ 中获取嵌入式资源的容器文件

ios - 是否可以在没有 Mac 的情况下为 iOS 制作 cordova CLI 应用程序?

python - 无法使用 python3 从 apache2 服务器运行 bash 脚本?

Bash 变量 SECONDS 立即扩展还是延迟扩展?