沉默npm运行脚本失败的错误

当你运行npm test并失败时,你会得到testing结果+一个错误信息,如下所示:

 npm ERR! Test failed. See above for more details. 

但是,我制作了一个名为lint的自定义脚本,如下所示:

 // package.json { // ... "scripts": { // ... definition for test ... "lint": "./node_modules/jsxhint/cli.js src/", } } 

好,很简单。 但是当你运行npm run lint并且失败的时候,而不是npm test的好看的错误,在npm test输出之后你会得到一个大的错误信息:

 npm ERR! Darwin 14.0.0 npm ERR! argv "node" "/usr/local/bin/npm" "run-script" "lint" npm ERR! node v0.10.32 npm ERR! npm v2.1.7 npm ERR! code ELIFECYCLE # and ~15 more lines... 

有没有办法让所有这些垃圾静音,所以我可以有一个干净的输出,如npm test脚本? 我看他们是如何在npm源代码中发现错误的,但是我不认为我可以添加一个自定义的命令,而不用像这样npm …希望我错了!

但是如果我是这样的,那么把这样的任务推到像Grunt这样的工具上会更好吗? 谢谢!

使用npm run --silent选项:

 $ npm run --silent test 

如果定义一个shell别名,那么input更less:

 $ alias run='npm run --silent' $ run test 

如果你不关心保存linter进程的返回码,你可以总是像这样configuration你的package.json

 { // ... "scripts": { // ... "lint": "eslint . || true", } } 

我刚刚试图弄清楚。 不是一个完美的答案,但它有一种工作,指定linting作为一个预testing脚本( 文档 )像这样:

 // package.json { // ... "scripts": { // ... definition for test ... "pretest": "./node_modules/jsxhint/cli.js src/", } } 

然后,当你第一次inputnpm test时,你只会从NPM中得到一个单行错误。 显然,这意味着如果你没有完成testing,你将无法运行testing。

另一种select是使用像Make, Grunt或Gulp这样的第三方任务运行者。

我只使用了Make,而且我认为这是最容易设置的(至less在OSX和Linux上,不知道Windows)。

在你的根目录下创build一个Makefile ,如下所示:

 lint: ./node_modules/.bin/jslint ./*.js # or whatever your lint command is test: ./node_modules/.bin/mocha test/*.js # or whatever your test command is .PHONY: lint test 

然后键入make test make lint运行这些命令。

您可以通过将stderrredirect到/ dev / null来消除错误。 例如:

 { "test": "karma start" (package.json) } 

运行:

 $ npm run test 2> /dev/null 

现在将所有npm错误发送到/ dev / null,但正常input仍将在控制台中可见。

因为错误是由npm抛出的,所以在非零状态退出后,做下面的事情是不够的:

  { "test": "karma start 2> /dev/null" } 

但您可以通过创build另一个任务使用stderrredirect来调用该任务来克服它:

  { "test": "karma start", "test:silent": "npm run test 2> /dev/null" } 

这将确保npm错误消息被隐藏