简体   繁体   中英

require inside new Function

I'm debugging a code that one of the past workers in my company wrote in order to do a cosmetic update and can't understand something.

The code compiles a string to a function using new Function(object) when object is my input. I'm trying to read a file inside my input like this - require("fs").readFileSync("myfile.txt") but the function throw an exception that require is not defined .

How can I access require inside new Function, or otherwise- how can I read a file content in a different way inside new Function ?

Thanks

If for whatever reason you need to use new Function() you can pass in a reference to fs or anything else with something like:

const fs = require('fs')
let someFn = new Function('fs', "let text = fs.readFileSync('test.txt', {encoding: 'utf8'}); console.log(text)")
someFn(fs)

You can also pass in require the same way, but that seems even uglier.

The problem is that when you create a function with new Function() , your function operates in Node's global scope. But in Node there are some names that are added to all modules that might appear global, but are not actually on the global object. These include __dirname , __filename , and require . The result is that functions created with new Function() can't access them directly.

Here's a simpler example. The first console.log works, but the one second throws a ReferenceError:

console.log(__dirname)
let someF = new Function("console.log(__dirname)")
someF()

For more see: https://nodejs.org/api/globals.html

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