Home > Blockchain >  Starting Node server from Scala app with environment variables
Starting Node server from Scala app with environment variables

Time:09-30

I am trying to start a Node server from a Scala app using a shell script but when I try to add environment variables I am getting the following error:

Exception in thread "main" java.io.IOException: Cannot run program "TEST_ENV_VAR=fake-key": error=2, No such file or directory

The code looks like this:

import java.nio.file.{Files, Path}
import scala.language.postfixOps

@main def app() =
    val path = Path.of(scala.sys.props.get("user.home").get   "/projects")
    
    s"TEST_ENV_VAR=fake-key node $path/node-server/server.js" !!

It looks like it is trying to run the environment variables instead of the server. Is there a way to get it to recognize them correctly? I have been able to run a node server successfully using this method when I don't include the environment variable.

Thank you!

CodePudding user response:

Here is an example that uses the scala.sys.process.Process object:

import java.io.File

import scala.sys.process.*

@main def app() =
  val file = File(scala.sys.props.get("user.home").get   "/projects")
  Process("node node-server/server.js", Some(file), "TEST_ENV_VAR" -> "fake-key").!!

CodePudding user response:

As @Luis Miguel has commented, KEY=value is a shell construct but sub-processes are launched without a shell. To work around that you can:

  • Launch a shell and have it invoke your command.
import scala.sys.process._

Seq( "sh"  //shell of choice
   , "-c"  //run the following command
   , s"TEST_ENV_VAR=fake-key node $path/node-server/server.js"
   ).!!   //start process, block until exit, return output as a String

OR

  • Launch your command directly but with a modified environment (which is what the shell does).
import scala.sys.process._

Process( s"node $path/node-server/server.js" //run command
       , None                        //default CWD
       , ("TEST_ENV_VAR","fake-key") //add this to environment
       ).!!

  • Related