如何将从远程服务器获取的javascript文件(我得到字符串)转换为Node.js中的常规javascript对象? 我知道我可以使用JSON.parse并将json字符串转换为dictionar,但在这里我得到的文件很多
exports.something = something{}
等等。
可以这样做,我使用node.js和express和mongoose。
答案 0 :(得分:0)
如果您需要动态(我的意思是在运行时)评估字符串中包含的javascript,您应该使用Function constructor。
例如:
var code = "function sayHello() {return 'hello !';} module.exports = sayHello()";
var executor = new Function(code);
try {
// the code in executor will search for global variables into global scope.
global.module = {};
executor();
// your results are here
console.log(global.module);
} catch (err) {
console.error('Failed to execute code:', err);
}
你必须明白:
变量传递和返回的示例:
var code = "function sayHello() {return something;} console.log(sayHello()); return true";
// Indicate that the something variable inside the code is in fact an argument
var executor = new Function("something", code);
try {
// pass 'hi!' as 'something' argument, display return
console.log(executor("hi !"));
} catch (e) {
console.error('fail', e);
}
输出:
> hi !
> true
不要使用eval()
(请记住:eval是邪恶的),因为它可以访问您的本地范围,并且可能成为您应用程序中的漏洞。