Set env var for Node JS when launching through VS Code - node.js

I have Node JS Azure function that when I run locally needs the NODE_TLS_REJECT_UNAUTHORIZED=0 environment variable needs setting for my code to work. This is because I am connecting to an emulated Cosmos DB running locally on my machine which require Node to allow for self signed certificates.
I only want this environment variable setting when I run locally as in production I will be using a real (i.e. non emulated) Cosmos DB instance. Rather than putting and #if debug in my code (or the equivalent for a Node Azure Function) I'd like my VS Code project to set the env var when it is launched.
I've trying following this answers advice but when VS Code launches the program the environment variable is not set as I get a runtime error in my code about self signed certificates not being authorised. My launch.json looks like this:
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to Node Functions",
"type": "node",
"request": "attach",
"port": 9229,
"preLaunchTask": "func: ",
},
],
"environment": [{
"name": "NODE_TLS_REJECT_UNAUTHORIZED",
"value": "0"
}],
}
If I set the env var directly in code using process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0 everything is fine. I don't know how I can get VS Code to set this, or if it is even possible.

Please update
"environment": [{
"name": "NODE_TLS_REJECT_UNAUTHORIZED",
"value": "0"
}],
To Be
"env": {
"name": "NODE_TLS_REJECT_UNAUTHORIZED",
"value": "0"
},
Also please check the alternatives.
You can Update package.json scripts to add all environment variables on start like "runLocal": "NODE_TLS_REJECT_UNAUTHORIZED=0 ... your start code " or You can use third party lib called dotenv
this is how it works
01- Create .env file
02- Write all your environment variables key=val NODE_TLS_REJECT_UNAUTHORIZED=0
03- Update package.json scripts to add "runLocal": "NODE_ENV=dev ... your start code "
04- Check if node NODE_ENV is equal dev then load the dotenv
05- Import module in case of node env is local and call config function require('dotenv').config()

Related

Unable to change environmental variables in node.js in Visual Studio Code

I'm new here and I'm new with this programming language, so maybe my question is something very obvious.
I am trying to set an environmental variable in Node.js in Visual Studio Code (for example NODE_ENV to production). I've tried setting it using an .env file and using the dotenv package. This does not seem to work, and when I try to print the variable to the console it prints 'undefined'. This is the part that I have included in the .env file:
NODE_ENV = production
This is a part of the js file that I try to run:
const path = require('path')
require('dotenv').config()
console.log(process.env.NODE_ENV)
When I run this 'undefined' gets printed to the console. I also tried passing the place of the file as an argument with the config for dotenv, like this. That did not work.
I even tried to set te environmental variables directly via launch.json like this:
"version": "0.2.0",
"configurations": [
{
"type": "pwa-node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${file}",
"env": {
"NODE_ENV" : "production",
}
}
]
}
That also did not work.
Why is this? Why isn't Visual Studio Code able to change the environmental variables?
Thanks in advance.
According to the docs of dotenv there should be no space between the variable name and its value.
The syntax is: VARNAME=VALUE
So your .env file should be
NODE_ENV=production

VS Code Extension - How to set NODE_EXTRA_CA_CERTS?

I am creating an extension for VS Code. In that, before connecting to database, I need to set the env variable NODE_EXTRA_CA_CERTS to path to certificate file. Normally, If I am running any javascript code(myFile.js) that connects to my database, I run following command in terminal -
export NODE_EXTRA_CA_CERTS='path-to-certificate-file'
node myFile.js
Now, my extension has code that connects to my database, but how do i set the env variable NODE_EXTRA_CA_CERTS before running the extension ?
I tried following ways but it didn't work -
Used process.env.NODE_EXTRA_CA_CERTS='path-to-certificate-file' inside extension code.
Set this env variable in launch.json
"configurations": [
{
"name": "Run Extension",
"type": "extensionHost",
"request": "launch",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/out/**/*.js"
],
"preLaunchTask": "${defaultBuildTask}",
"osx": {
"env": {"NODE_EXTRA_CA_CERTS":"path-to-certificate-file"}
}
}
I added this line in my .zshrc file
export NODE_EXTRA_CA_CERTS='path-to-certificate-file' .
How env variables are set for VS Code Extension? Is there any reason or am i doing anything wrong which is why it isn't working ?

AWS Toolkit + VSCode local testing

I'm trying to figure out how to use AWS toolkit for vscode. I go to the AWS extension and click Create New SAM Application, point to project directory and it creates a hello world function. Above it, it says Add Debug Configuration. I click that, choose nodejs 12.x and save the launch.json, but I don't get the run option. It still says Add Debug Configuration for some reason. How can I run my lambda functions locally in the console?
The launch.json file generates, but I can never run the code.
launch.json
{
"configurations": [
{
"type": "aws-sam",
"request": "direct-invoke",
"name": "new test:app.lambdaHandler (nodejs12.x)",
"invokeTarget": {
"target": "code",
"projectRoot": "new test/hello-world",
"lambdaHandler": "app.lambdaHandler"
},
"lambda": {
"runtime": "nodejs12.x",
"payload": {},
"environmentVariables": {}
}
}
]
}
I also tried navigating to the hello-world directory in terminal and executing node app.js, but it doesn't return anything
What am I doing wrong? I appreciate the help!
Make sure you have SAM CLI install in local, here are the instructions for installation https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html
Then run the command sam local start-api.
You should be able to access the api at http://127.0.0.1:3000/hello
You can also do the same via vscode by selecting Run > Run without debugging (shortcut: ctrl + F5)

Debugging nuxtjs .vue Files On the Server in Docker

I currently have a nuxt app setup as a univeral app in which I'm hosting using Docker. I've got pretty much everything working, the debugger attaches and finds local variables just fine when walking through middleware and api calls, but when debugging the asyncData method in the .vue file I can't see any of the local variables and my breakpoint keeps moving to the .catch line:
I also get a bunch of other random things in the current context, which in this case is "Module"??
I've added this line to my nuxt.config.js file as well to make sure it uses the correct source maps:
/*
** Build configuration
*/
build: {
/*
** You can extend webpack config here
*/
extend(config, ctx) {
console.log(`IsClient: ${ctx.isClient}`);
console.log(`isDev: ${ctx.isDev}`);
if (ctx.isDev) {
config.devtool = ctx.isClient ? 'source-map' : 'inline-source-map'
}
}
}
Also here is my .vscode config:
{
// 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": [
{
"name": "Docker: Attach to Node",
"type": "node",
"request": "attach",
"remoteRoot": "/usr/share/nginx/app",
"port": 9229,
"address": "localhost",
"localRoot": "${workspaceFolder}/app",
"protocol": "inspector",
"restart": true,
"sourceMaps": true
}
]
}
Also, here is the command I use to start the container:
node --inspect=0.0.0.0:9229 \
./node_modules/.bin/nuxt \
& nginx -g "daemon off;" \
I've tried a lot of different things including using babel-register and starting it with babel-node since its transpiled, but none of those methods worked.
Is there anything I'm missing here? Can we just not debug .vue files on the server when creating a universal app?
UPDATE
I switched to Webstorm and for whatever reason the debugging works flawlessly. I guess that is the difference between using an IDE and a text editor.
vs code attach inspector when your nuxt app is already started.
To see whats happen in server side, vs code have to launch your nuxt app.
Add this script to your package.json:
...
scripts: {
"dev": "nuxt,
"dev-debug": "node --inspect node_modules/.bin/nuxt",
...
}
...
In .vscode config or .vscode/launch.json:
"configurations": [{
"type": "node",
"request": "launch",
"name": "Launch nuxt",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run",
"dev-debug"
],
"port": 9229
},
...
And finally, extend the build in nuxt.config.js to add source maps when we are running in development mode and ensure the correct type for both the client and server.
build: {
extend(config, ctx) {
if (ctx.isDev) {
config.devtool = ctx.isClient ? 'source-map' : 'inline-source-map'
}
}
}
It's work for me on localhost, but I'm not sure it's working with remote root...
Also, it's not a perfect solution. I saw sometimes breakpoint jump from different line. I think this is because vs code cannot handle same lines in source and inline-source.
Alternative way:
To debug only javascript of a single file component (.vue), it's possible to extract the javascript part in an external .js file, and import it with <script src="./path-to-js"></script>.

Hosting environment why is it set to Production, Difference between host.json and local.settings.json

I have two questions on .net core applications for functions. I am using blobtrigger.
1) When I run my project locally I get this 'Hosting environment' on the command prompt console, I want to understand where is this variable set and how can I change it to development. Its misleading since I am only developing locally.
[5/23/2019 7:00:20 PM] Host started (773ms)
[5/23/2019 7:00:20 PM] Job host started
Hosting environment: Production
Content root path: C:Myproject\bin\Debug\netcoreapp2.1
Now listening on: http://0.0.0.0:7071
2) What is the difference between host.json and local.settings.json. When can host.json be used? So far I have only used local.settings.json and when I publish to azure I am creating configurations mentioned in local.settings.json but Host.json is not used it looks like. Whats the purpose of host.json file is.
"Hosting environment" on the console comes from the environment variable ASPNETCORE_ENVIRONMENT. When this variable is not set, it defaults to "Production".
It's set here: HostingEnvironment.cs
The reason behind this default is described in this github issue.
This variable is popular in dotnet core web apps, but it is not mentioned in official docs in Azure functions (I am not sure why). If you write a for loop and output all the environment variables to console from within a function, you will find that this variable is not set by default - neither in production, nor when running in Visual Studio.
If you wish to define this variable locally, you have a few different ways.
Setting the environment variable via command line:
setx ASPNETCORE_ENVIRONMENT "Development"
Defining this in Properties\launchSettings.json:
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
Defining this in local.settings.json:
"Values": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
Note that this variable is not automatically defined to production when you publish your app to azure. You will have to define this variable in "Configuration" -> "Application Settings" in Azure portal.
In azure functions there appears to be another similar environment variable called AZURE_FUNCTIONS_ENVIRONMENT. This one is defined by default locally.
AZURE_FUNCTIONS_ENVIRONMENT = Development
This is not defined in production by default, and can be defined in the azure portal.
Difference between host.json and local.settings.json:
host.json is to configure pre-defined settings that function app infrastructure understands. It applies to both local and production environments. It doesn't allow custom settings though. local.settings.json on the other hand is useful for defining custom settings. host.json is committed into source control, but local.settings.json is usually left out of source control, and is considered to be a good location to store secrets and connection strings for development.
More details here about the differences: https://learn.microsoft.com/en-us/azure/azure-functions/functions-develop-vs#create-an-azure-functions-project (scroll to the end of that section)
host.json reference
local.settings.json reference
You can add "ASPNETCORE_ENVIRONMENT": "Development" in the local.settings.json, to change the hosting environment:
As you know, local.settings.json is just for local testing and will not be published to azure portal. For host.json(which will be published to azure), you can configure settings like loglevel(if you want to log) in azure portal. More details, please refer to this article of host.json.
Sometimes, most times, Microsoft has strange ways of doing things... we as the community have to either find a way around them, or conform. Well, if you are one of those who cant survive the idea to conforming to something that doesn't make sense, here is a solution:
Delete local.settings.json
Create two files (or many, each for your environment), and name them {environment}.local.settings.json eg: development.local.settings.json and production.local.settings.json
Create a task to copy your current environment file to local.settings.json
Here we go again: we got to duplicate tasks...
[
{
"label": "use development.local.settings.json",
"command": "cp development.local.settings.json local.settings.json",
"type": "shell",
"options": {
"cwd": "${workspaceFolder}/..."
}
},
{
"label": "use production.local.settings.json",
"command": "cp production.local.settings.json local.settings.json",
"type": "shell",
"options": {
"cwd": "${workspaceFolder}/..."
}
},
{
"label": "azure-func-development",
"type": "func",
"dependsOn": [
"use development.local.settings.json",
"build"
],
"dependsOrder": "sequence",
"options": {
"cwd": "${workspaceFolder}/.../bin/Debug/netcoreapp2.2"
},
"command": "host start",
"isBackground": true,
"problemMatcher": "$func-watch"
},
{
"label": "azure-func-production",
"type": "func",
"dependsOn": [
"use production.local.settings.json",
"build"
],
"dependsOrder": "sequence",
"options": {
"cwd": "${workspaceFolder}/.../bin/Debug/netcoreapp2.2"
},
"command": "host start",
"isBackground": true,
"problemMatcher": "$func-watch"
}
]
Don't get tired, we are not finished duplicating, yet...
Lets duplicate the launch.json configurations:
[
{
"name": "[Development] Attach to Azure .NET Functions",
"type": "coreclr",
"request": "attach",
"preLaunchTask": "azure-func-development",
"processId": "${command:azureFunctions.pickProcess}"
},
{
"name": "[Production] Attach to Azure .NET Functions",
"type": "coreclr",
"request": "attach",
"preLaunchTask": "azure-func-production",
"processId": "${command:azureFunctions.pickProcess}"
}
]

Resources