简体   繁体   中英

How to convert javascript file fetched from remote server( I get string) to regular javascript object in Node.js?

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:

  1. the dynamic code is executed within the global scope. That is, not access to local variables
  2. global variable in the dynamic code must be initialized before execution
  3. variables can also be passed as argument of the function itself
  4. return of the dynamic code will be accessible as return of the function

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM