Running app in nodejs

Intro

It is easy to use Fluence JS in NodeJS applications. You can take full advantage of the javascript ecosystem and at the save time expose service to the Fluence Network. That makes is an excellent choice for quick prototyping of applications for Fluence Stack.

Calc app example

Lets implement a very simple app which simulates a desk calculator. The calculator has internal memory and implements the following set of operations:
    Add a number
    Subtract a number
    Multiply by a number
    Divide by a number
    Get the current memory state
    Reset the memory state to 0.0
First, let's write the service definition in aqua:
1
-- service definition
2
service Calc("calc"):
3
add(n: f32)
4
subtract(n: f32)
5
multiply(n: f32)
6
divide(n: f32)
7
reset()
8
getResult() -> f32
Copied!
Now write the implementation for this service in typescript:
1
import { Fluence } from "@fluencelabs/fluence";
2
import { krasnodar } from "@fluencelabs/fluence-network-environment";
3
import { registerCalc, CalcDef } from "./_aqua/calc";
4
5
class Calc implements CalcDef {
6
private _state: number = 0;
7
8
add(n: number) {
9
this._state += n;
10
}
11
12
subtract(n: number) {
13
this._state -= n;
14
}
15
16
multiply(n: number) {
17
this._state *= n;
18
}
19
20
divide(n: number) {
21
this._state /= n;
22
}
23
24
reset() {
25
this._state = 0;
26
}
27
28
getResult() {
29
return this._state;
30
}
31
}
32
33
const keypress = async () => {
34
process.stdin.setRawMode(true);
35
return new Promise<void>((resolve) =>
36
process.stdin.once("data", () => {
37
process.stdin.setRawMode(false);
38
resolve();
39
})
40
);
41
};
42
43
async function main() {
44
await Fluence.start({
45
connectTo: krasnodar[0],
46
});
47
48
registerCalc(new Calc());
49
50
console.log("application started");
51
console.log("peer id is: ", Fluence.getStatus().peerId);
52
console.log("relay is: ", Fluence.getStatus().relayPeerId);
53
console.log("press any key to continue");
54
await keypress();
55
56
await Fluence.stop();
57
}
58
59
main();
Copied!
As you can see all the service logic has been implemented in typescript. You have full power of npm at your disposal.
Now try running the application:
1
> node -r ts-node/register src/index.ts
2
3
application started
4
peer id is: 12D3KooWLBkw4Tz8bRoSriy5WEpHyWfU11jEK3b5yCa7FBRDRWH3
5
relay is: 12D3KooWSD5PToNiLQwKDXsu8JSysCwUt8BVUJEqCHcDe7P5h45e
6
press any key to continue
Copied!
And the service can be called from aqua. For example:
1
const peer ?= "12D3KooWLBkw4Tz8bRoSriy5WEpHyWfU11jEK3b5yCa7FBRDRWH3"
2
const relay ?= "12D3KooWSD5PToNiLQwKDXsu8JSysCwUt8BVUJEqCHcDe7P5h45e"
3
4
func demoCalculation() -> f32:
5
on peer via relay
6
Calc.add(10)
7
Calc.multiply(5)
8
Calc.subtract(8)
9
Calc.divide(6)
10
res <- Calc.getResult()
11
<- res
Copied!
Last modified 29d ago
Copy link