简体   繁体   English

要求内部新功能

[英]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. 当对象是我的输入时,代码使用new Function(object)将字符串编译为函数。 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 . 我正在尝试读取输入中的文件,如下所示 - require("fs").readFileSync("myfile.txt")但该函数抛出了一个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 ? 如何在新函数内部访问require ,或者如何在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: 如果由于某种原因你需要使用new Function()你可以通过以下方式传递对fs或其他任何内容的引用:

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. 您也可以通过在require以同样的方式,但似乎甚至丑陋。

The problem is that when you create a function with new Function() , your function operates in Node's global scope. 问题是当您使用new Function()创建函数时,您的函数在Node的全局范围内运行。 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. 但是在Node中,有一些名称被添加到可能看起来是全局的所有模块中,但实际上并不在全局对象上。 These include __dirname , __filename , and require . 这些包括__dirname__filenamerequire The result is that functions created with new Function() can't access them directly. 结果是使用new Function()创建的new Function()无法直接访问它们。

Here's a simpler example. 这是一个更简单的例子。 The first console.log works, but the one second throws a ReferenceError: 第一个console.log工作,但是一秒抛出一个ReferenceError:

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

For more see: https://nodejs.org/api/globals.html 有关更多信息,请参阅: https//nodejs.org/api/globals.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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