我们目前正在将 UI 项目(总共 3 个)的构建转移到 Grunt。为了简化过渡,我想提供一个 bat 文件,它将为每个项目运行 npm install
,但是我想知道在发出此命令时是否出了问题。这只是我追求的糖衣,我知道 npm 会回显错误,但我想为我的团队中不熟悉 npm
和 node< 的成员提供一些更简单的消息
.
有没有办法检查 npm 是否遇到错误并随后停止 bat 文件? 例如,如果未安装 Node ,我只需检查 %ERRORLEVEL%
为 1。如果是这种情况,我会回显一些指令并退出执行。我遇到的问题是,在 npm install
期间发生错误时,%ERRORLEVEL%
未设置为 1。
感谢任何帮助!
最佳答案
试试这个方法。
在我运行 npm 的批处理文件中(我们称之为 test.bat)我有这个:
@ECHO OFF
call npm install jquery 2<&1 || exit /b 1
ECHO Continuing...
现在,当我运行 test.bat 时,我看到了这个:
jquery@2.1.3 node_modules\jquery
Continuing...
但是,如果我将“jquery”更改为不存在的包的名称(即模拟 npm 故障,如您所说,不会影响 %ERRORLEVEL%),我明白了这个:
npm ERR! Windows_NT 6.2.9200
npm ERR! argv "C:\\Program Files (x86)\\nodejs\\\\node.exe" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "asdasdas"
npm ERR! node v0.10.33
npm ERR! npm v2.3.0
npm ERR! code ETARGET
npm ERR! notarget No compatible version found: undefined@'*'
npm ERR! notarget No valid targets found.
npm ERR! notarget Perhaps not compatible with your version of node?
npm ERR! notarget This is most likely not a problem with npm itself.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! Please include the following file with any support request:
npm ERR! C:\Projects\XXXX\npm-debug.log
请注意,“ECHO Continuing”行未执行。
“2<&1
”部分似乎采用 STDERR 输出并将其重定向到 STDOUT:http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true
"... handle 2 (that is, STDERR), from the ipconfig command to handle 1 (that is, STDOUT)..."
我从 https://stackoverflow.com/a/10359327/68432 中获取了这个解决方案
关于node.js - 在bat文件中查询npm错误状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20882628/