-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample8.js
More file actions
109 lines (67 loc) · 2 KB
/
Copy pathexample8.js
File metadata and controls
109 lines (67 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
console.log(`
POT JS Example 8: Node.js, in-memory, explict init, asynchronous
This is a self-contained web app, serving a page to receive input,
returning the results.
open http://localhost:3000
`)
const http = require("http")
const qs = require("querystring")
const fs = require("fs")
require("./lib/wasm_exec")
const form = `<!DOCTYPE html><head><meta charset="UTF-8"></head>
<pre>
POT JS Example 8: Node.js Web App Server
<form method=post action="http://localhost:3000">
key <input name=key>
value <input name=value>
<input type=submit name=button value=put>
<hr />
key <input name=search>
<input type=submit name=button value=get>
value <input name=result>
</form>
<hr />
</pre>
<script> console.log('see server log in terminal') </script>
<pre>
`
var kvs
var go = new Go()
globalThis.potVerbosity = 3
WebAssembly.instantiate(fs.readFileSync("lib/pot.wasm"), go.importObject)
.then((r) => { go.run(r.instance) })
global.onPotInitialized = async () => {
bee = process.argv[2]
batch = process.argv[3]
kvs = new pot.Kvs(bee, batch)
// There is no catching of early calls of put() and get()
// in this example, which in theory could race the loading
// of pot.wasm and the creation of kvs.
}
async function put(key, value) {
await kvs.put(key, value)
return `put ${key}: ${value}`
}
async function get(search) {
value = await kvs.get(search)
return `get ${search}: ${value}
<script>
document.getElementsByName('result')[0].value = '${value}'
</script>`
}
const server = http.createServer((request, response) => {
var log = ''
var body = ''
request.on('data', (data) => body += data)
.on('end', async () => {
const { button, key, value, search } = qs.parse(body)
switch(button) {
case 'put': log = await put(key, value) ; break
case 'get': log = await get(search)
}
response.writeHead(200)
response.end(form + log + `\n</pre>`)
})
})
.listen(3000, '127.0.0.1')
console.log('srv: listening at http://127.0.0.1:3000')