-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
46 lines (39 loc) · 1.16 KB
/
index.js
File metadata and controls
46 lines (39 loc) · 1.16 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
'use strict';
const path = require('path');
const nodeEval = require('node-eval');
const JSON5 = require('json5');
/**
* Evals file contents as expressions, JSON or commonJS module.
*
* @param {string} contents Contents to eval
* @param {string} [filename] Path to file with contents
* @param {Object} [context] Objects to provide into execute method
* @returns {*}
*/
module.exports = (contents, filename, context) => {
const ext = filename ? path.extname(filename) : '.js';
if (ext === '.json' || ext === '.js') {
return nodeEval(contents, filename, context);
}
if (ext === '.json5') {
return tryCatch(() => JSON5.parse(contents), err => {
err.message = `${filename}: ${err.message}`;
throw err;
});
}
throw new Error(`Not support extension "${ext}" to eval`);
};
/**
* Execute function inside try-catch function with try-catch is not optimized so we made this helper.
*
* @param {Function} tryFn function to try
* @param {Function} catchFn function to catch
* @returns {*}
*/
function tryCatch(tryFn, catchFn) {
try {
return tryFn();
} catch(e) {
catchFn(e);
}
}