Search code examples
node.jsubuntuspawn

How to run Linux/Ubuntu commands(not executables) from Nodejs


I have been running executables using spawn in nodejs all this while, now when i am trying to use spawn to run ubuntu commands like unset, export etc, they dont seem to work. I guess cause it is looking for executables. I even tried exec, that does not seem to work too. Any tips?

I have an ubuntu device running node, from the UI i need to set/unset env variables for proxy, e.g. http_proxy and no_proxy. Apart from export what other way can i do it via node? The env variables should be set system wide not just for the current process.


Solution

  • Environment variables only exist in memory and are local to a process. For any running process, only the process itself can make changes to the set of environment variables "belonging" to that process, but those changes will not propagate to existing child or parent processes.

    In short: you cannot change an environment variable that will apply to all processes on your system (not even from a regular shell).

    You can only set an environment variable so it becomes available for newly created child processes (child processes by default inherit the set of environment variables from their parent), but that's about it.

    If you have control over how the processes that require those specific environment variables are started, you could write the value for those variables to a file (from Node) and source that file right before the other processes are started, but it really depends on the actual use case whether this is a usable option.