Я пытаюсь написать систему плагинов для моего CLI-приложения node.js.
Приложение должно получать описания из файлов .json, а фактическую функцию - из файла .js, все они находятся в определенной папке.
Приложение проверяет эту папку при запуске и требует каждый файл .json
На основе данных json загружается файл .js, содержащий module.exports = {functions}
Как получить доступ к этим функциям из основного файла в другое время (после ввода пользователя или после 10-секундного таймера))?
function fakeuserinput(x, y) {
console.log(math.divide(x, y));
})
}
setTimeout(fakeuserinput(10, 2), 10000);
(дополнительный вопрос: есть ли лучший способ, чем использовать eval ()?)
main.js
//commands is an array of all .json files
commands.forEach(function(cmd){
// eval(cmd.module) = require('./plugins/'+cmd.module+'.js'); doesnt work
require('./plugins/'+cmd.module+'.js');
console.log(cmd.name+'\n'+cmd.module);
// console.log(eval(cmd.module).eval(cmd.name)(10, 2));
console.log(eval(cmd.name)(10, 2));
})
math.js
module.exports = {
multiply: function (x, y) {
return x * y;
},
divide: function (x, y) {
return x / y;
},
add: function (numbers) {
return numbers.reduce(function(a,b){
return a + b
}, 0);
},
subtract: function (numbers) {
return numbers.reduce(function(a,b){
return a - b
}, 0);
},
round: function (x) {
return Math.round(x);
},
squared: function (x) {
return x * x;
},
root: function (x) {
return Math.sqrt(x);
}
}
divide.json
{
"name": "divide",
"module": "math",
"commands": [
[
"how much is (integer) / (integer)",
"how much is (integer) divided by (integer)",
"what is (integer) / (integer)",
"what is (integer) divided by (integer)",
"(integer) / (integer)",
"(integer) divided by (integer)"
]
],
"description": "Divide x by y"
}
Я могу загружать функции, не зная их имени, например:
main.js
//commands is an array of all .json files
commands.forEach(function(cmd){
console.log(cmd.name);
console.log(eval(cmd.name)(10, 2));
})
function divide(x, y) {
return x / y;
}
function multiply(x, y) {
return x * y;
}
но я застреваю, пытаясь добраться до функции, когда она находится в module.exports другого файла.
код для файлов json -> массив
var folder = './plugins/';
fs.readdir(folder, function (err, files) {
if (err) {
console.log('Couldn\'t read folder contents: '+err.message);
return;
}
files.forEach(function (file, index) {
if (file.substr(-5) == '.json') {
let path = folder+file;
fs.readFile(path, 'utf8', function (err, data) {
if (err) {
console.log('Couldn\'t read JSON file: '+err.message);
}
commands.push(JSON.parse(data));
console.log('Command added: '+file.substr(0, file.length-5));
});
}
});
});
сообщение об ошибке:
ReferenceError: математика не определена