Skip to content

Commit 94a9ebb

Browse files
committed
Update example
1 parent 5928717 commit 94a9ebb

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

JavaScript/application.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@
77
// Print from the global context of application module
88
console.log('From application global context');
99

10-
module.exports = function() {
10+
const fs = require('fs');
11+
console.dir({ fs });
12+
13+
module.exports = () => {
1114
// Print from the exported function context
1215
console.log('From application exported function');
1316
};

JavaScript/framework.js

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,26 @@
44
// appication runtime, load an application code and passes a sandbox into app
55
// as a global context and receives exported application interface
66

7+
const PARSING_TIMEOUT = 1000;
8+
const EXECUTION_TIMEOUT = 5000;
9+
710
// The framework can require core libraries
811
const fs = require('fs');
912
const vm = require('vm');
1013

1114
// Create a hash and turn it into the sandboxed context which will be
1215
// the global context of an application
13-
const context = { module: {}, console };
16+
const context = {
17+
module: {}, console,
18+
require: (name) => {
19+
if (name === 'fs') {
20+
console.log('Module fs is restricted');
21+
return null;
22+
}
23+
return require(name);
24+
}
25+
};
26+
1427
context.global = context;
1528
const sandbox = vm.createContext(context);
1629

@@ -20,13 +33,27 @@ fs.readFile(fileName, (err, src) => {
2033
// We need to handle errors here
2134

2235
// Run an application in sandboxed context
23-
const script = vm.createScript(src, fileName);
24-
script.runInNewContext(sandbox);
36+
let script;
37+
try {
38+
script = new vm.Script(src, { timeout: PARSING_TIMEOUT });
39+
} catch (e) {
40+
console.log('Parsing timeout');
41+
process.exit(1);
42+
}
43+
44+
try {
45+
script.runInNewContext(sandbox, { timeout: EXECUTION_TIMEOUT });
46+
const exported = sandbox.module.exports;
47+
console.dir({ exported });
48+
} catch (e) {
49+
console.log('Execution timeout');
50+
process.exit(1);
51+
}
2552

2653
// We can access a link to exported interface from sandbox.module.exports
2754
// to execute, save to the cache, print to console, etc.
2855
});
2956

3057
process.on('uncaughtException', (err) => {
31-
console.log('>>>' + err.stack);
58+
console.log('Unhandled exception: ' + err);
3259
});

0 commit comments

Comments
 (0)