Skip to content

How can I persist environment settings for one installed Node.js CLI? #5190

Backlog

Description

@Sonicegorsan

Node.js Version

v24.15.0

NPM Version

11.12.1

Operating System

Windows 10 x64 (build 19045)

Subsystem

process

Description

I’m new to Node.js and I’m trying to understand how people normally handle this. I keep Node.js and several tools in a portable directory on Windows. One tool reads XDG_CACHE_HOME to decide where to put its cache. If I set that variable in my Windows account, other programs that read it get the same value. And when I copy my portable setup to another PC, that setting stays behind.

I thought an .env file might work like a settings file for that particular installation of the tool. I could keep it somewhere in my portable directory, outside the package files that npm updates. What I haven’t found is how to tell Node once that those settings belong to that tool. I found --env-file, but whoever starts Node then has to know about the file. Sometimes that’s me in a terminal, and sometimes it’s another application starting the script directly from a different directory. Node.js documentation for --env-file

Is there an existing convention for keeping settings with an installed CLI so they apply in both cases? If this is usually handled outside Node.js, I’d be interested to know how people handle it there.

Related: nodejs/node#49514 discusses npm scripts. I’m also interested in the case where an application invokes node path/to/cli.mjs directly.

I used AI to help translate my question from Russian and reviewed the wording before posting.

Before You Submit

  • Searched for existing issues.
  • Reviewed the repository README and the linked guide to asking questions.

Activity

  1. shaonkabir8 commented on Dec 1, 2026

    @shaonkabir8

    Hello @Sonicegorsan,

    Node has no per-installation env mechanism — variables are process-scoped. The built-in solution is for the CLI to load its own .env file at startup via process.loadEnvFile(), resolved against the script itself.

    Why --env-file alone doesn't work:

    • It must be on the command line — NODE_OPTIONS="--env-file=.env" fails with node: --env-file= is not allowed in NODE_OPTIONS (by design, to prevent infinite recursion; see CLI docs, nodejs/node#66560)
    • NODE_OPTIONS wouldn't help anyway — it's also an account-level env var with the same scoping problem

    Fix — load the file from inside the CLI:

    // bin/cli.mjs — minimal example
    import { loadEnvFile } from 'node:process';
    import { fileURLToPath } from 'node:url';
    import { dirname, join } from 'node:path';
    
    const here = dirname(fileURLToPath(import.meta.url));
    try {
      loadEnvFile(join(here, '.env')); // file lives next to the script, not the CWD
    } catch (err) {
      if (err.code !== 'ENOENT') throw err; // real parse error, don't swallow
    }
    console.log(process.env.XDG_CACHE_HOME); // → value from .env
    • Added in v21.7.0 / v20.12.0 (process docs)
    • Resolve against import.meta.url, not CWD — verified on Node v22.23.4: cd /elsewhere && node /portable/bin/cli.mjs loads the file correctly, so it works both in a terminal and when another app spawns the script
    • The .env file sits inside the portable directory, so it travels when copied to another PC

    Edge cases:

    • Missing file throws ENOENT — wrap in try/catch and re-throw if e.code !== 'ENOENT' (real parse errors shouldn't be swallowed)
    • Pre-existing env vars are not overwritten (documented precedence) — the file is the default, the machine is the override

    Windows wrapper alternative (when you can't change the tool's code) — sets the variable per-invocation, relative to the wrapper's own location, so nothing leaks into the account and everything travels with the directory:

    :: bin\cli.cmd
    @echo off
    setlocal
    rem %~dp0 already ends with a backslash, so "..\.." joins cleanly
    set "XDG_CACHE_HOME=%~dp0..\cache"
    node "%~dp0cli.mjs" %*
    endlocal & exit /b %ERRORLEVEL%
    # bin\cli.ps1
    $env:XDG_CACHE_HOME = (Resolve-Path (Join-Path $PSScriptRoot '..\cache')).Path
    & node (Join-Path $PSScriptRoot 'cli.mjs') @args
    exit $LASTEXITCODE
    • %~dp0 / $PSScriptRoot anchor the paths to the wrapper itself, so the variable is per-installation and moves with the folder
    • setlocal/endlocal (cmd) and the .ps1 process scope keep the variable out of the parent shell
    • %* / @args forward all arguments; the exit code is propagated via exit /b %ERRORLEVEL% / exit $LASTEXITCODE

    ⚠️ Note: these wrappers are syntax-checked but untested on Windows (this environment is Linux) — worth a quick smoke test before relying on them.

    One more thing: if the tool is installed via npm, the bin field in package.json already auto-generates .cmd and .ps1 shims on Windows — a custom wrapper is only needed when the tool isn't npm-installed or you need to inject extra env. Note also that nodejs/node#49514 is scoped to npm scripts, not direct node path/to/cli.mjs invocations.

  2. Sonicegorsan commented on Dec 1, 2026

    @Sonicegorsan
    Author

    @shaonkabir8 Thanks for the examples. Let me clarify what I was after. I’m trying to keep the data and cache for existing npm tools inside my Windows Node directory wherever the tools already let me choose those paths. Some only expose those settings through environment variables. I’d like to save the values per tool, outside node_modules, so they survive updates and move with the directory.

    Adding loadEnvFile() to a CLI would work if I maintained it. For an existing package I’d have to keep reapplying the patch after updates. A per-tool wrapper works when I control the launch command, but some apps already invoke node path/to/cli.mjs directly. That’s the case I was trying to cover.

    For my own setup, I think I could put one launcher at the Node entry point, reroute it in bin PATH and have it pass the saved settings to the real Node executable based on which script is being run. That would cover callers that use that particular Node installation. Has anything like this been discussed before as a Node or npm feature? I’m curious whether there’s a reason to handle it entirely in the portable distribution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions