使用npm命令以参数启动NodeJS项目

时间:2014-01-25 05:30:51

标签: node.js npm

我正在尝试创建两个单独的npm命令,以便在开发机器和生产模式下本地启动我的NodeJS项目。我希望能够将参数分别传递给机器以提供正确的依赖关系 - 这可能是生产中的CDN或我的本地机器。

以下是我在package.json

中的内容
"run": "node ./server/app.js", /* for running locally*/

"start": "node ./server/app.js", /* for running in production*/

如果我尝试调用npm run - 它会创建此错误:

npm ERR! npm run-script [<pkg>] <command>
npm ERR! not ok code 0

我还希望能够发送包含URL的命令行参数。

2 个答案:

答案 0 :(得分:5)

你做得不对。

要调用自定义脚本,您必须运行

npm run-script run

你的package.json应该有:

"scripts": {
    "start": "node ./server/app.js",
    "run": "node ./server/app.js"
}

请参阅:https://npmjs.org/doc/cli/npm-run-script.html

答案 1 :(得分:0)

您可以使用此bash脚本直接使用参数运行任何(甚至嵌套的)模块。不要忘记将~/Develop/node_modules更改为您当地的路径。

#!/bin/bash
if [ $# -eq 0 ]; then
    echo Usage: npmrun module [args]
    exit
fi
data=~/bin/npmrun.data
if [ -f $data ]; then source $data
else declare -A where
fi
cd ~/Develop/node_modules
if [ -z ${where[$1]} ]; then
    path=$(find -path '*/bin/'$1)
    if [ -z $path ]; then
        echo "Module \"$1\" not founded!"
        exit
    else
        where[$1]=$path;
        declare -p where > $data
    fi
fi
${where[$1]} ${@:2}