1

In node I want to set START_DIR on process.env to process.cwd().

How to that within scripts package.json?

I can't use env file for example. this app not using env file loader and I can't change that.

for example:

"scripts": {
    "start": "set SOMEDIR=process.cwd() && node app",

....

console.log('res', process.env.START_DIR);
raxinaga
  • 411
  • 1
  • 6
  • 18

1 Answers1

1

Just to be clear, process.env represents the environment of the Node process at runtime, so whatever environment variables are visible to the Node process can be accessed in your modules as process.env.WHATEVER_VAR.

And why not just call process.cwd() from your app's code? It will return the path from which you execute the node command, or in this case npm start. It would be helpful to know more about what you're trying to accomplish, as I don't see why you would want to do what I think you're trying to do.

If you really want to do exactly what you described, you can use node -e "console.log('something')" To output something to the shell. Here's how it might look when you run npm start from a bash shell in the directory you want process.cwd() to return. (I'm not sure of the Windows equivalent):

"start": "export START_DIR=$(node -e \"console.log(process.cwd());\") && node app"

There are other options though. You could refer to the operating system's built-in variable representing the working directory. Looks like you may be using Windows, so that variable's name would be CD. I believe the full command would look something like this:

set SOMEDIR=%CD% && node app

Or, if you're starting the process from a bash shell (Linux and MacOS):

export SOMEDIR=$PWD && node app

You can also just access these variables directly in your scripts using process.env.CD or process.env.PWD.

The only danger with this method is that it assumes CD / PWD hasn't been manually set to some other value. In Windows, one way to circumvent this is to create a batch file wherever you're calling npm start from. In the file, execute the same command but replace %CD% with %~dp0, which refers to the path containing the file. Then set start to a Windows command to execute the file, something like call ./file.bat.

Similarly, in a bash environment create a shell script and use $(dirname $0) instead of $PWD. Make it executable with chmod +x name_of_file and set start to bash ./name_of_file.

One last thing: if the name of the variable doesn't matter, package.json can tell npm to create environment variables prefixed by npm_config_. More info in the npm config documentation.

rmccreary
  • 76
  • 6