sourcetip

윈도우즈 PowerShell에서 Node.js 환경 변수 전달

fileupload 2023. 9. 5. 20:43
반응형

윈도우즈 PowerShell에서 Node.js 환경 변수 전달

다음과 같은 방법으로 PowerShell을 사용하여 Node.js에 환경 변수를 전달하려고 합니다.

C:\Users\everton\my-project> $env:MY_VAR = 8000 node index.js

하지만 PowerShell에서 다음 오류가 발생합니다.

토큰 'node' 예기치 않은 식 또는 문

설정하기MY_VAR먼저 다음과 같이 앱을 실행합니다.

C:\Users\everton\my-project> $env:MY_VAR="8000" ; node index.js

환경변액할수있다습니세에 접속할 수 .MY_VAR東京의 index.js타고

process.env.MY_VAR

참고: PowerShell은 명령 범위 환경 변수를 직접 지원하지 않습니다.위 명령은 해당 PowerShell 세션의 환경 변수를 설정합니다.

제 답변에는 Node.js 및 npm 라이브러리를 사용해야 합니다.

...또는 모호한 WTF 언어 스크립트 작성의 어려움을 없애고 명령 범위(및 교차 플랫폼) Node.js 스크립트 중 하나를 사용합니다.

  • cross-env (인라인용)

    cross-env MYVAR=MYVALUE node index.js
    
  • env-cmd (.env 파일에서)

    env-cmd .env node index.js
    

    와 함께

    #.env file
    MYVAR=MYVALUE
    

참고: Node.js가 이미 설치되어 있다고 가정할 수 있는 경우 - 정의에 따라 호출하는 경우node의사을고의 합니다.npmCyril CHAPON의 유용한 답변에 나와 있는 것처럼 도우미 패키지.
답변은 PowerShell 내부의 일반적인 솔루션에 초점을 맞춥니다.

tl;dr

# Set env. variable temporarily, invoke the external utility, 
# then remove / restore old value.
$oldVal, $env:MYVAR = $env:MYVAR, 8000; node index.js; $env:MYVAR = $oldVal
# Scoped alternative that uses a *transient* helper variable.
& { $oldVal, $env:MY_VAR = $env:MY_VAR, 8000; node index.js; $env:MY_VAR = $oldVal }

더 간단하게, 만약 존재하지 않는다면,MY_VAR복원해야 하는 값입니다.

$env:MYVAR=8000; node index.js; $env:MYVAR=$null

도우미 기능을 기반으로 한 설명 및 대안은 아래를 참조하십시오.


하리크리쉬난의 효과적인 답변을 보완하기 위해:

PowerShell에는 POSIX와 유사한 셸이 제공하는 환경 변수를 전달하는 명령 범위 방법과 동등한 기능이 없습니다(그러나 PowerShell v7의 경우, 반드시 동일한 구문을 사용하는 것은 아님). 예를 들어 GitHub 이슈 #3316에서 논의되고 있습니다.

 # E.g., in *Bash*: 
 # Define environment variable MY_VAR for the child process being invoked (`node`)
 # ONLY; in other words: MY_VAR is scoped to the command being invoked
 # (subsequent commands do not see it).
 MY_VAR=8000 node index.js

파워셸에서는 하리크리쉬난의 답변에서 알 수 있듯이 먼저 환경 변수정의한 다음 별도 문에서 외부 프로그램을 호출해야 합니다.$env:MY_VAR="8000"; node index.js 는 올바른 PowerShell 솔루션이지만 세션 나머지 기간 동안 범위를 유지하는 은 가치가 없습니다(프로세스 레벨에서 설정됨).

▁with로 호출된 스크립트 하는 경우에도 하십시오.&하위 범위는 환경 변수가 아닌 PowerShell 변수에만 적용되기 때문에 하위 범위를 만드는 것은 여기서 도움이 되지 않습니다.

물론 호출 후 환경 변수를 수동으로 제거할 수 있습니다.
Remove-Item env:MY_VAR아니면 그냥$env:MY_VAR = $null이것이 상단의 첫 번째 명령어가 보여주는 것입니다.


여러 환경 변수를 설정하거나 여러 명령을 호출하는 경우 보다 체계적인 대안은 다음과 같이 호출되는 스크립트 블록을 사용하는 것입니다.&:

& { $oldVal, $env:MY_VAR = $env:MY_VAR, 8000; node index.js; $env:MY_VAR = $oldVal }

이를 통해 다음과 같은 이점을 얻을 수 있습니다.

  • { ... }스크립트 블록의 명령에 대해 명확하게 볼 수 있는 그룹화를 제공합니다. 를 사용하여 호출됩니다.&로컬 범위를 생성하여 도우미 변수$oldVal블록을 종료하면 자동으로 범위를 벗어납니다.

  • $oldVal, $env:MY_VAR = $env:MY_VAR, 8000의 이전 값을 저장합니다(있는 경우).$env:MY_VAR$oldVal값을 로 변경하는 동안8000여러 변수를 한 번에 할당하는 이 기술(일부 언어에서는 할당 파괴라고 함)은 "여러 변수 할당" 섹션에서 설명합니다.

또는 아래의 도우미 기능을 사용하거나 이 관련 답변에 설명된 대로 접근 방식을 사용합니다.


명령 범위 환경 수정을 위한 도우미 기능.

아래에서 도우미 기능을 정의하면(기능 정의는 호출되기 전에 배치해야 함) 다음과 같이 사용자 환경의 명령 범위 수정을 수행할 수 있습니다.

# Invoke `node index.js` with a *temporarily* set MY_VAR environment variable.
Invoke-WithEnvironment @{ MY_VAR = 8000 } { node index.js }

Invoke-WithEnvironment() 소스 코드:

function Invoke-WithEnvironment {
<#
.SYNOPSIS
Invokes commands with a temporarily modified environment.

.DESCRIPTION
Modifies environment variables temporarily based on a hashtable of values,
invokes the specified script block, then restores the previous environment.

.PARAMETER Environment
A hashtable that defines the temporary environment-variable values.
Assign $null to (temporarily) remove an environment variable that is
currently set.

.PARAMETER ScriptBlock
The command(s) to execute with the temporarily modified environment.

.EXAMPLE
> Invoke-WithEnvironment @{ PORT=8080 } { node index.js }

Runs node with environment variable PORT temporarily set to 8080, with its
previous value, if any 
#>
  param(
    [Parameter(Mandatory)] [System.Collections.IDictionary] $Environment,
    [Parameter(Mandatory)] [scriptblock] $ScriptBlock
  )
  # Modify the environment based on the hashtable and save the original 
  # one for later restoration.
  $htOrgEnv = @{}
  foreach ($kv in $Environment.GetEnumerator()) {
    $htOrgEnv[$kv.Key] = (Get-Item -EA SilentlyContinue "env:$($kv.Key)").Value
    Set-Item "env:$($kv.Key)" $kv.Value
  }
  # Invoke the script block
  try {
    & $ScriptBlock
  } finally {
    # Restore the original environment.
    foreach ($kv in $Environment.GetEnumerator()) {
      # Note: setting an environment var. to $null or '' *removes* it.
      Set-Item "env:$($kv.Key)" $htOrgEnv[$kv.Key]
    }
  }
}

언급URL : https://stackoverflow.com/questions/43024906/pass-node-js-environment-variable-with-windows-powershell

반응형