使用 env 变量获取缓存位置

Get cache location with env variable

我使用以下方法获取 NPM 缓存位置:

  cache_location="$(npm get cache)"

但是,这个值是否也由我可以读取的环境变量表示?

类似于 NPM_CACHE_LOCATION?

https://docs.npmjs.com/cli/cache

简短回答: 这取决于 when/how 你想要访问它,因为没有环境变量,(例如 NPM_CACHE_LOCATION),同时可用npm 不是 运行宁。

您需要像现在一样调用 npm config get cachenpm get cache

但是,一旦 npm 运行ning 将配置参数放入带有 npm_ 前缀的环境中。

下面演示了这个...


发现哪些环境变量可用:

作为找出 npm 放置在环境中的环境变量的一种方法,您可以在 npm 脚本中使用 printenv。例如在 package.json 添加:

...
"scripts": {
  "print-env-vars": "printenv | grep \"^npm_\""
},
...

然后运行以下命令:

npm run print-env-vars

通过环境变量获取缓存位置:

在控制台的结果日志中(即在 运行ning npm run print-env-vars 之后),您会看到列出了 npm_config_cache 环境变量。它是这样写的:

npm_config_cache=/Users/UserName/.npm

docs 中指出:

configuration

Configuration parameters are put in the environment with the npm_config_ prefix. For instance, you can view the effective root config by checking the npm_config_root environment variable.

注意:运行 printenv | grep "^npm_" 直接通过 CLI return 没什么。

正在使用环境变量访问缓存位置:

  1. 您可以通过 npm-script 访问缓存位置,例如:

    "scripts": {
      "cache-loc-using-bash": "echo $npm_config_cache",
      "cache-loc-using-win": "echo %npm_config_cache%"
    },
    

    请参阅 cross-var 了解如何使用跨平台语法。

  2. 通过 Nodejs 脚本访问 npm 缓存位置。例如:

    const cacheLocation = process.env.npm_config_cache;
    console.log(cacheLocation)
    

    注意: 需要通过 npm 脚本调用此节点脚本才能使 process.env.npm_config_cache 可用。通过命令行 运行ning 调用它,例如node ./somefile.js 将 return undefined - 这进一步证明了带有 _npm 前缀的参数仅在 npm 为 运行ning 时才放入环境中。


不理想,但是您当然可以使用 export 设置自己的环境变量:

export NPM_CACHE_LOCATION="$(npm get cache)"

unset删除它:

unset NPM_CACHE_LOCATION