I have inherited an application that currently does not run locally. I believe the issue is that it cannot find the environment variables.
My launch.json looks like this:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Chat Web Server",
"program": "${workspaceFolder}\\dist\\server.js",
"preLaunchTask": "npm build",
"envFile": "${workspaceFolder}\\Env\\Local.env",
"runtimeArgs": ["--inspect=127.0.0.1:9264"], // , "-r", "dotenv/config"
"sourceMaps": true
}
]
}
When running the application I get an error from this constructor
public constructor(Topic: string) {
this.Topic = Topic;
console.log("Service Bus Connection String");
console.log(process.env.ServiceBusUri );
this.Client = ServiceBusClient.createFromConnectionString(
process.env.ServiceBusUri || ""
);
this.SenderClient = this.Client.createTopicClient(Topic);
this.Sender = this.SenderClient.createSender();
}
TypeError: Missing Endpoint in Connection String. at Object.create (C:_Development\xxx\node_modules@azure\amqp-common\dist\index.js:1564:19) at Function.createFromConnectionString (~\node_modules@azure\service-bus\dist\index.js:6281:52) at new ServiceBus (C:_Development\xxx\dist\Lib\Utils\ServiceBus.js:44:54) at Object. (C:_Development\xxx\dist\server.js:50:26)
There is a value in local.env
ServiceBusUri=Endpoint=sb://xxxxx.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=zzzzzzzzzzzzzzzzzzzzzzzzzz=
When outputting this to the console the value of process.env.ServiceBusUri
is undefined.
I have limited knowledge of TypeScript and how I should reference the file but this is how the folder structure appears
Any help on what I need to do to get the values read correctly will be very much appreciated.
CodePudding user response:
In order to read local .env
files, you should use dotenv
package provided from npm (https://www.npmjs.com/package/dotenv).
You should then, right at the beginning of your application, include the following code:
require('dotenv').config({ path: '/custom/path/to/Env/Local.env' })
Of course you can make this code depending on your current environment by using an if
statement to check process.env
. This way no environment variables used in production would be overwritten. The reason this code works in azure is probably that the environment variables used are injected by azure itself.
After that the values should be available during runtime like implemented (e.g. process.env.ServiceBusUri
).