How to convert javascript file fetched from remote server( I get string) to regular javascript object in Node.js ? I understand that I can use JSON.parse and convert json string to dictionar, but here I get file with lot of
exports.something = something{}
and so on.
Is possible to do this, I am using node.js and express and mongoose.
If you need to dynamically (I mean at runtime) evaluate javascript contained in a string, you should use the Function constructor .
For example:
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);
}
You have to understand that:
An example of variable passing and return:
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);
}
Outputs :
> hi !
> true
Don't use eval()
(remember: eval is evil), because it will give access to your local scope, and can became a breach in your application.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.