set an environmental variable in node.js and then use it in terminal?

前端 未结 1 1450
臣服心动
臣服心动 2021-01-12 00:40

well I\'d like to add an environmental varible during the execution of a js file using node.js.

Something like: process.env[\'VARIABLE\'] = \'value\';

I\'m

相关标签:
1条回答
  • 2021-01-12 01:04

    The unix permissions model will not allow a child process (your node.js app) to change the environment of its parent process (the shell running inside your terminal). Same applies to current working directory, effective uid, effective gid, and several other per-process parameters. AFAIK there's no direct way to do what you are asking. You could do things like print the command to set it to stdout so the user can easily copy/paste that shell command into their terminal, but your best bet is to explain the broader problem you are trying to solve in a separate question and let folks tell you viable ways to get that done as opposed to trying to change the parent process's environment.

    One possible workaround would be something is simple as running your node program from the terminal like this:

    export SOME_ENV_VAR="$(node app.js)"
    

    and have app.js just print the desired value via process.stdout.write.

    Second hack would be a wrapper shell script along these lines:

    app.sh

    #!/bin/bash
    echo app.sh running with SOME_ENV_VAR=${SOME_ENV_VAR}
    echo "app.sh running app.js"
    export SOME_ENV_VAR="$(node app.js)"
    exec /bin/bash
    

    app.js

    console.log("Some Value at " + Date());
    

    Running this in an interactive shell in your terminal

    echo $SOME_ENV_VAR
    
    exec ./app.sh
    app.sh running with SOME_ENV_VAR=
    app.sh running app.js
    
    echo $SOME_ENV_VAR 
    Some Value at Thu Mar 27 2014 08:13:01 GMT-0600 (MDT)
    

    Maybe these will give you some ideas to work with.

    0 讨论(0)
提交回复
热议问题