Book Image

Elixir Cookbook

By : Paulo Pereira
Book Image

Elixir Cookbook

By: Paulo Pereira

Overview of this book

Table of Contents (16 chapters)
Elixir Cookbook
About the Author
About the Reviewers

Executing code in a different node

It is possible to define a function in a node and execute it in another one.

In this recipe, we will be connecting two nodes and will define a function to print a greeting message with the greeter name (in this case, the node's full name). Afterwards, we will execute the function in both nodes!

Getting ready

To be able to execute a function in another node, we will start by following the steps from the previous recipe. We will create two nodes and connect them together. Repeat the steps from the previous recipe to get started.

How to do it…

With both nodes up and running and connected, we are ready to start:

  1. Define a function in node one:

    iex([email protected])4> greeting_node = fn() -> IO.puts("Hello from #{inspect(Node.self)}") end
    #Function<20.90072148/0 in :erl_eval.expr/5>
  2. It's time to instruct the second node to run the function we defined in node one:

    iex([email protected])21> Node.spawn(:"[email protected]", greeting_node)