I feel like asking a silly question but I have googled it for a while and can't find a satisfying answer. SO doesn't such discussion either, only How to set NODE_ENV to production/development in OS X and How can I set NODE_ENV=production on Windows?
To run a command after another in one line we normally join them by ;
( or &&
)
So I had assumed I should run command like this PORT=3000 ; node server.js
PORT=3000 ; node server.js
or export PORT=3000; node server.js
export PORT=3000; node server.js
, just like PORT=3000 ; echo $PORT
PORT=3000 ; echo $PORT
But we just put a space between PORT=3000 node server.js
(without ;
or &&
) and PORT is read into process.env.PORT.
How does shell make nodejs get environment variables? It will be better if someone can show nodejs codes.
----- update ------
The reason I was puzzled with this shell syntax (according to my limited knowledge) is that I think the general format for a Unix command line is
command options(s) filename(s)
The space in between is used to separate command from option and filename. So how can it be used to separate 2 commands as well?
I checked nodejs document and found the answer https://nodejs.org/api/process.html#process_process_env
So it is environ , not 2 separated commands,
Bourne-style shells support the syntax
NAME=value command
to create an environment variable definition only in the scope of the process that executes command.
Or as bash manual 3.7.4 explained.
For python , it is os.environ['NAME']
This is also the reason why it won't work on windows: How can I set NODE_ENV=production on Windows?
Notes for Windows users, as a comment there by daw "set NODE_ENV=production && " adds a trailing space to the variable and don't use single/double quote.
I feel quite embarrassed that I almost wanted to delete my question. I keep it here in case someone else may also have this doubt. Or someone else can further explain environ or how node read it into process.env object.
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.