1

I want to load module from raw text, such as

var code = "exports.name = 'hello'";
// Is there such a function?
var name = requrie_from_code(code).name;
console.log(name); // should be 'hello'

I think it can be done by first saving the code into a temporary file such as tmpcode.js and then require('./tmpcode.js'). But is there a way to do it directly ?

user1668903
  • 407
  • 5
  • 11

1 Answers1

0

To interpret JavaScript strings as JavaScript themselves, you should probably use the eval function... But heed my warning, if there is any form of user-input, or if you need complex debugging, you're going to run into some walls, and it will hurt.

JavaScript's eval takes string input and interprets it, simple as that... Here is an example:

var test = "var example = 5;";
eval(test);
console.log(example);

Simple as that...


Here is some instances where eval can be dangerous!

Lets say you had the following code for some reason:

dbModule.syncConnection(function(database){
  eval("var test = '" + someUserInput + "'");
});

With this, a user can easily bypass what you've set by inputting something like this:

"'; database.query('DELETE EVERYTHING MWAHAHA'); '"

The eval function would then turn into:

var test = ''; database.query('DELETE EVERYTHING MWAHAHA'); ''

... So this just one simple example on how eval can be dangerous.

Otherwise, there isn't really any other safe way to check JavaScript before interpreting it, unless you run through the string yourself and disallow certain possible attacks....

But remember, anything that can go wrong will go wrong. And with user-input, there is infinite possibilities.