Edit 2014.10.30: It's possible to pass args to npm run
as of npm 2.0.0
(编辑2014.10.30: 从npm 2.0.0开始可以将args传递给npm run
)
The syntax is as follows:
(语法如下:)
npm run <command> [-- <args>]
Note the necessary --
.
(注意必要的--
。)
It is needed to separate the params passed to npm
command itself and params passed to your script.(需要将传递给npm
命令本身的参数和传递给脚本的参数分开。)
So if you have in package.json
(所以如果你在package.json
)
"scripts": {
"grunt": "grunt",
"server": "node server.js"
}
Then the following commands would be equivalent:
(那么以下命令将是等效的:)
grunt task:target
=> npm run grunt -- task:target
(grunt task:target
=> npm run grunt -- task:target
)
node server.js --port=1337
=> npm run server -- --port=1337
(node server.js --port=1337
=> npm run server -- --port=1337
)
To get the parameter value, see this question .
(要获取参数值, 请参阅此问题 。)
For reading named parameters, it's probably best to use a parsing library like yargs or minimist ;(为了读取命名参数,最好使用yargs或minimist之类的解析库;)
nodejs exposes process.argv
globally, containing command line parameter values, but this is a low-level API (whitespace-separated array of strings, as provided by the operating system to the node executable).(nodejs全局公开process.argv
,其中包含命令行参数值,但这是一个低级API(由空格分隔的字符串数组,由操作系统提供给节点可执行文件)。)
Edit 2013.10.03: It's not currently possible directly.
(编辑2013.10.03:目前无法直接进行。)
But there's a related GitHub issue opened on npm
to implement the behavior you're asking for.(但是在npm
上有一个相关的GitHub问题,可以实现您要求的行为。)
Seems the consensus is to have this implemented, but it depends on another issue being solved before.(似乎已经达成共识,但这取决于之前要解决的另一个问题。)
Original answer: As a some kind of workaround (though not very handy), you can do as follows:
(原始答案:作为一种变通办法(尽管不是很方便),您可以执行以下操作:)
Say your package name from package.json
is myPackage
and you have also
(假设您来自package.json
的包名称是myPackage
并且您还拥有)
"scripts": {
"start": "node ./script.js server"
}
Then add in package.json
:
(然后添加package.json
:)
"config": {
"myPort": "8080"
}
And in your script.js
:
(并在您的script.js
:)
// defaulting to 8080 in case if script invoked not via "npm run-script" but directly
var port = process.env.npm_package_config_myPort || 8080
That way, by default npm start
will use 8080. You can however configure it (the value will be stored by npm
in its internal storage):
(这样,默认情况下, npm start
将使用8080。但是,您可以对其进行配置(该值将由npm
存储在其内部存储中):)
npm config set myPackage:myPort 9090
Then, when invoking npm start
, 9090 will be used (the default from package.json
gets overridden).
(然后,当调用npm start
,将使用9090( package.json
的默认值将被覆盖)。)