[英]Nodejs can't find includes when running from relative path
I have nodejs code in the_second_folder but I want to run it from the root folder. 我在the_second_folder代码的NodeJS但我想从根文件夹运行它。 When I run the code from the_second_folder I get no errors, but when I run the code from the root folder nodejs crashes because of includes.
当我从the_second_folder运行代码时,我没有收到任何错误,但是当我从根文件夹运行代码时,nodejs由于包含而崩溃。 Here is the code:
这是代码:
require('rootpath')(); //does not work
var file_to_include = "file.js";
eval(fs.readFileSync(file_to_include)+'');
This only works when I run the code from the_second_folder (where it is) but fails when running from the root folder (-1 in the folder tree). 这仅在我从the_second_folder (在此处)运行代码时起作用 ,但在从根文件夹(文件夹树中为-1)运行时失败。 The error is precisely about the inclusion of file_to_include
该错误恰好与包含file_to_include有关
What I'd like to know is how can I run the node script in a relative folder scope even when called from root folder. 我想知道的是,即使从根文件夹调用该脚本,也如何在相对文件夹范围内运行节点脚本。
EDIT 编辑
file_to_include ABSOLUTE_PATH
Error: ENOENT, no such file or directory 'file_to_include.js'
...
at Object.<anonymous> (/root/the_second_folder/socket.io/lib/client.js:3:9)
...
at Object.<anonymous> (/root/the_second_folder/socket.io/lib/index.js:12:14)
Now the error happens in socket.io... any idea on this? 现在错误发生在socket.io中...对此有任何想法吗?
You can use the global __dirname
, which returns the directory of the current script. 您可以使用全局
__dirname
,它返回当前脚本的目录。
You can then do something like: 然后,您可以执行以下操作:
var file_to_include = "file.js";
eval(fs.readFileSync(path.join(__dirname,file_to_include))+'');
But may i ask why you are eval()
ing a JS file instead of just require()
ing it? 但是我想问一下为什么您要
eval()
一个JS文件而不是仅仅require()
它吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.