[英]Nodejs can't find includes when running from relative path
我在the_second_folder代码的NodeJS但我想从根文件夹运行它。 当我从the_second_folder运行代码时,我没有收到任何错误,但是当我从根文件夹运行代码时,nodejs由于包含而崩溃。 这是代码:
require('rootpath')(); //does not work
var file_to_include = "file.js";
eval(fs.readFileSync(file_to_include)+'');
这仅在我从the_second_folder (在此处)运行代码时起作用 ,但在从根文件夹(文件夹树中为-1)运行时失败。 该错误恰好与包含file_to_include有关
我想知道的是,即使从根文件夹调用该脚本,也如何在相对文件夹范围内运行节点脚本。
编辑
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)
现在错误发生在socket.io中...对此有任何想法吗?
您可以使用全局__dirname
,它返回当前脚本的目录。
然后,您可以执行以下操作:
var file_to_include = "file.js";
eval(fs.readFileSync(path.join(__dirname,file_to_include))+'');
但是我想问一下为什么您要eval()
一个JS文件而不是仅仅require()
它吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.