node.js - 确定从模块运行的npm或yarn脚本

标签 node.js npm argv yarnpkg npm-scripts

假设我的 package.json 文件中有以下脚本:

{
  "start": "node index.js",
  "start-with-flag": "node index.js -f"
}

index.js中,我有一个console.log(process.argv),上面的脚本输出以下内容:

$ npm run start
[ '/usr/local/Cellar/node/8.4.0/bin/node',
  '/Users/.../test_app/index.js' ]

$ npm run start-with-flag
[ '/usr/local/Cellar/node/8.4.0/bin/node',
  '/Users/.../test_app/index.js',
  '-f' ]

是否可以检索我在 index.js 中运行的脚本(startstart-with-flag)的值>?

最佳答案

您可以使用 npm_lifecycle_event 访问当前执行的脚本环境变量。

命令

$ npm run start-with-flag

index.js

console.log(process.env.npm_lifecycle_event)  // start-with-flag

package.json

{
  "scripts": {
    "start": "node index.js",
    "start-with-flag": "node index.js -f"
  }
}

关于node.js - 确定从模块运行的npm或yarn脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47187029/

相关文章:

c - 如何将文件 fscanf 转换为多维数组

c - 如何在 C 程序中设置命令行参数,以便在用户键入 "ps aux"时可见?

c - 有没有来自标准输入的东西?

javascript - 如何在 Waterline ORM 中设置数据库连接字符串

AWS EC2 上的 Node.js RESTful API 服务器与 AWS API 网关

angular - 错误!解析时 JSON 输入意外结束

javascript - Node.js错误: require is not defined in clientside js file

angularjs - Satellizer 和推特登录

javascript - io.emit 与 socket.emit

node.js - 使用NodeJS安装后无法识别包 'mongodb'