简体   繁体   中英

How to export env variable in node.js

I like my node.js so much, that I want to use it is my bash start up script ~/.bashrc , but I do not know how to export variable.

Currently I have to use this approach:

export PS1=`node ~/PS1.js`
export PS2=`node ~/PS2.js`
export PATH=`node ~/PATH.js`

instead I want .bashrc look have

#!/usr/local/bin/node
//do something, define functions
export_var('PS1', PS1())
export_var('PS2', PS2())
export_var('PATH', generatePATH())

process.env.PATH = something does not export , only sets for the currently executing process, which is node itself.

Node.js will run in an separate process which gets a copy of the environment. You cannot change the environment of you parent process (the one executing .bashrc).

But the following question has an answer for you: Can a shell script set environment variables of the calling shell?

You can write a new script file from within node.js and call it via source .

One possible way is to use JS to print out the export statements, then in shell to use eval to evaluate it in the current shell.

eg test.js

#!/usr/bin/env node
console.log('export A=40; export B=10');

In the shell:

eval `./test.js`
echo $A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM