'How do I use existing module with new Function() constructor?
I have a universal eventEmitter in my app called eventEmitter.js.
eventEmitter.js:
const EventEmitter = require('events').EventEmitter
const events = new EventEmitter()
module.exports = events
I want to use it in my new Function() constructor.
fnConstructor.js:
let fn = `const events = require('./eventEmitter')
events.on('hi', ()=>console.log('hi'))
events.emit('hi')`
let func = new Function(fn)
func()
This produces an error:
undefined:3
const events = require('./eventEmitter')
^
ReferenceError: require is not defined
Which I believe is expected since the new Function() constructor basically sandboxes the code execution away from the global scope.
I know I can make this work with eval(), but all of my research about eval() says not to use it for security reasons, that it performs very poorly, and that new Function() is recommended.
Is there any way to require existing application modules inside of new Function() scripts? If not, what are some other alternatives? Or, would I be okay with eval() knowing that the code I'll be executing will only be my code, despite the potential performance hits?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
