-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrun.js
executable file
·99 lines (85 loc) · 2.3 KB
/
run.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* 沙箱mock数据
* @author liuliandong ([email protected])
*/
var vm = require('vm');
var fs = require('fs');
var path = require('path');
// 沙箱程序路径
exports.sourceDir = './AO-Debug/response';
//等待实现
exports.runphp = function(code, path, param) {
};
/**
* 在沙箱运行JS模拟程序
* 防止挂掉服务器,更安全,即时生效,不需要重启服务器
* @param {String} code 代码内容
* @param {String} path 请求path
* @param {Object} param Post请求参数
* @return {Object} 沙箱程序运行的输出结果
*/
exports.runJS = function(code, path, param) {
var msgCache = [];
function print(args) {
var args = arguments;
for (var i = 0; i < args.length; i++) {
msgCache.push(args[i]);
}
}
function dump(object) {
msgCache.push(object);
}
var context = {
param: param,
path: path,
console: {
log: dump,
dump: dump
}
};
vm.runInNewContext(code, context);
return (msgCache.length == 1) ? msgCache[0]: msgCache;
};
/**
* 支持重写该方法
* @param {String} pathName 请求path
* @param {Object} param 请求POST参数
* @return {Buffer/String} 返回数据
*/
exports.getContent = function(pathName, param) {
var content = '';
var fileName = pathName.replace(/\//g, '_') + '.js';
var filePath = path.join( exports.sourceDir, fileName);
if (fs.existsSync(filePath)) {
content = fs.readFileSync(filePath);
}
return content;
};
/**
* 打包结果
* 修改输出格式,或者修改结果
* @param {Object} data 输出结果
* @return {Object}
*/
exports.pack = function(data) {
var rst = {
"status": 200,
"data": data,
"error": {}
}
return rst;
};
/**
* 获得结果- 数据入口
* @param {String} pathName 请求路径
* @param {Object} param 请求参数
* @return {Object} 要输出的结果
*/
exports.getResult = function(pathName, param) {
var content = exports.getContent(pathName);
var result = exports.runJS(content, pathName, param);
if (exports.pack) {
result = exports.pack(result);
}
return result;
};