Tuesday, September 22, 2020

In this Blog post I’ll show you how create, use and configure Azure function using JavaScript.

First go to your azure Portal and when you are there, click in the new button and type function app in the search box

And chose function app from the filter results.

Fill out fields and finally click on the blue create button.

Click on create custom function and in the choose a template page, select JavaScript as language and choose Manual trigger JavaScript.

Keep the default name for simplicity and click create.

You will be presented with a default function. Click run and verify that for a successful message on the logs

This input is coming from the test values in the upper right section.

You can try changing the input value to get familiar with this initial function template.

Here of course you can create extra JavaScript functions and call them from your main entry point function.

Perhaps you would like to place your code in helper libraries where your functions will live.

The way you can do this is by clicking on the View files tab and click the add button, this will add a new file; to make this interesting lest create a function that provides access to environment variables.

To import this library just add a regular import statement on top of the in index.js.

add this code to print the variables object in the logs.

var variables = library.getEnvironmentVariables();
context.log(`EnvVars: ${JSON.stringify(variables, null, 2)}`);

Click save and run and inspect the logs.

Look for the environment variables being print on the logs.

Now let’s see how to include and use a node package in this function. I’ll import the library that I probably use in every single node application I’ve written, “lodash”.

To import lodash write this import statement

As you can see we don’t have a node-modules folder or loadsh.js file in our files yet.

To include node packages in this function.

First go to Kudu:

Then you will see the current files on your function.

In the lower part of the screen you will see a console.

From this console we can run commands.

First run npm init to create a package.json file and answer the question with default answers to create the package.json file.

Now type:

npm install lodash -S

This will install lodash and update package.json by adding lodash as a dependency

Now let’s comeback to azure function and use lodash.

Notice that now we have a node_modules folder with lodash installed.

To prove lodash is up and running let’s add this line to your function, save it and run it and confirm on the logs this message is printed.