-
Notifications
You must be signed in to change notification settings - Fork 11
/
example.js
77 lines (59 loc) · 1.85 KB
/
example.js
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
const Sandbox = require('./dist').default;
const path = require('path');
const sandbox = new Sandbox({ require: path.join(process.cwd(), 'example-functions.js') });
const timeout = 5000;
const run = (code) => {
return sandbox.execute({ code, timeout });
};
const example1 = `
setResult({value: [21, 22]});
`;
// call a custom synchronous host function
const example2 = `
setResult({value: addNumbers(1, 2)});
`;
// call a custom asynchronous host function
const example3 = `
addNumbersAsync(1, 2, function(error, value) {
setResult({error, value});
});
`;
// synchronous http request
const example4 = `
const response = httpRequest({uri: 'https://gist.githubusercontent.com/zhm/39714de5e103126561da5f60e0fe0ce2/raw/46c1114c9f78a75d67dc4100d7e5e4d63ea5c583/gistfile1.txt'});
setResult({value: response.body});
`;
// asynchronous http request
const example5 = `
var response = httpRequest({uri: 'https://gist.githubusercontent.com/zhm/39714de5e103126561da5f60e0fe0ce2/raw/46c1114c9f78a75d67dc4100d7e5e4d63ea5c583/gistfile1.txt'}, (err, res, body) => {
setResult({value: body});
});
`;
// a lot of data
const example6 = `
let data = '';
for(let i = 0; i < 2e4; ++i) {
data += Math.random().toString();
}
simpleAsync(data, function(error, value) {
setResult({error, value: value.length});
});
`;
const runExample = async (code) => {
const { error, value } = await run(code);
if (error) {
console.error(error);
}
return value;
};
(async () => {
for (let i = 0; i < 10; ++i) {
console.log('example 1:', await runExample(example1));
console.log('example 2:', await runExample(example2));
console.log('example 3:', await runExample(example3));
console.log('example 4:', await runExample(example4));
console.log('example 5:', await runExample(example5));
console.log('example 6:', await runExample(example6));
}
sandbox.shutdown();
})();