【问题标题】:Why does `DEBUG=foo node index.js` fails in `scripts` section of `package.json`为什么`debug=foo node index.js`在`package.json`的`scripts`部分失败
【发布时间】:2017-05-13 17:49:27
【问题描述】:

我使用的是 Windows 10,但我使用的是 git bash。从git bash 运行时:

DEBUG=foo node index.js

它工作正常并设置环境变量DEBUG。但如果我把它放到package.jsonscripts 部分:

  "scripts": {
    "start": "DEBUG=foo node index.js"
  },

并从git bash 运行以下命令,我收到以下错误:

$ npm start

> nodejs@1.0.0 start C:\Users\maksym.koretskyi\Desktop\nodejs
> DEBUG=foo node index.js

'DEBUG' is not recognized as an internal or external command,
operable program or batch file.

为什么会有这种行为?

【问题讨论】:

  • 您的错误是由于在Windows 环境(注意batch 关键字)而不是bash shell 下执行的指令造成的。
  • 谢谢,我就是这么想的。你知道为什么即使我从git bash 运行npm start 还是在Windows 环境下执行DEBUG=foo node index.js 吗?
  • 能否再次确认一下,如果node安装正确,可能会检查Git bash中的$PATH是否有安装node的路径
  • 它应该有,因为 DEBUG=foo node index.jsgit bash 执行得很好

标签: node.js bash package.json


【解决方案1】:

您好像在 Windows 上运行它。

假设你让 Bash 像你说的那样工作,我会写一个脚本:

#!/bin/bash
DEBUG=foo node index.js

称为例如run-debug 并使用:

"scripts": {
    "start": "bash run-debug"
},

package.json 中确保DEBUG=foo node index.js 命令由Bash 解释,而不是command.com 或Windows 中调用的任何shell。见Issue #6543: npm scripts shell select

如果您希望它甚至在没有 Bash 的系统上运行,为了获得最大的跨平台兼容性,最好使用 Node 脚本而不是 shell 脚本:

"scripts": {
    "start": "node run-debug.js"
},

在这种情况下,run-debug.js 可能包含以下内容:

let env = Object.create(process.env);
env.DEBUG = 'foo';
spawn('node', ['app.js'], {env});

另见:

【讨论】:

  • 谢谢,这可能是一个解决方案,但我想了解为什么 npm 在 Windows 下运行命令,而不是 git bash
【解决方案2】:

是的,确实,我发现了以下thread 并指出:

shell 配置变量仅由 npm explore 命令使用, 它分叉了一个子shell。它不是用来让你使用的, 比如说,在 Windows 上使用 bash,或者在 Powershell 和 cmd.exe 之间切换。 脚本始终由 Unix 上的 shebang 行运行,而 cmd.exe 在 窗户

所以这似乎是设计使然,没有办法改变它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2014-08-28
    • 1970-01-01
    • 2018-12-15
    • 2022-01-20
    • 2020-12-04
    相关资源
    最近更新 更多