在bat文件中查询npm错误状态
我们正在将我们的UI项目(共3个)构build到Grunt。 为了简化转换,我想提供一个bat文件,它将为每个项目运行npm install
,但是我想知道在发出这个命令时是否出现了问题。 我之后只是糖衣,我知道npm会回应错误,但是我希望我的团队中不熟悉npm
和node
的成员能够更轻松地发送消息。
有没有办法检查npm是否遇到错误,并随后停止bat文件? 例如,如果节点没有安装,我只是检查%ERRORLEVEL%
是1.如果是这种情况,我回显一些指令并退出执行。 我遇到的问题是,在npm install
过程中发生错误时, %ERRORLEVEL%
未设置为1。
任何帮助感激!
一些命令不更新ERRORLEVEL
。 我真的不知道如何node.js安装,但我遇到了与NSLOOKUP
命令相同的问题。 NPM
似乎在自己的实例中运行,这可能解释了为什么它不更新ERRORLEVEL
。
我可以build议你使用简单的redirect将命令的输出写入某个日志文件,然后在文件中search指示安装不成功的文本。 假设您正在查找单词“错误”发生的次数。 batch file可能如下所示:
cmd /c "npm install > install.log 2>&1" for /f %%a in ('type install.log ^| find /c /i "err"') do set err=%%a if "%err%" GTR "0" echo ERROR was encountered during installation
一步一步解释一下:
-
cmd /c "npm install > install.log 2>&1"
执行安装并将输出redirect到
install.log
。 注意2>&1
在最后。 这是为了将错误输出和标准保存到单个文件。cmd /c
的原因是closuresnpm
创build的实例。 没有这个我不能做这个工作。 -
for /f %%a in ('type install.log ^| find /c /i "err"') do set err=%%a
请通过install.log并将variables
err
设置为包含“err”的行数。 -
if "%err%" GTR "0" echo ERROR was encountered during installation
如果
err
大于0,则echo
自定义消息。
另一种方法是对你需要的node.js部分执行一个基本的testing,比如执行一些npm
命令并检查它们的输出(与上面类似)。 不过,我不是node.js的专家,在这一点上不能引导你。
试试这个方法。
在运行npm的batch file(我们称之为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输出并将其redirect到STDOUT: http : //www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx? mfr =真正
“…处理2(即STDERR),从ipconfig命令处理1(即STDOUT)…”