[英]nodejs can't find my own module realted to parent path
I have a tree like this. 我有一棵这样的树。
folder1
file1.js
folder2
file2.js
index.js
I require my file1 from withing index.js 我需要通过index.js使用我的file1
from file 1 i want to require file2 从文件1我想要求文件2
if I do const file2= require('../folder2/file2.js');
如果我做const file2= require('../folder2/file2.js');
it works 有用
if I do it dynamically so 如果我动态地这样做
const myFiles = fs.readdirSync('../folder2').filter(file => file.endsWith('.js'));
for (const file of myFiles )
{
const myFile = require(`../folder2/${file}`);
}
I got this 我懂了
return binding.readdir(pathModule._makeLong(path), options.encoding);
^
Error: ENOENT: no such file or directory, scandir 'displaying a wrong path here'
If in my readdir i do a simple ./
如果在我的readdir中,我做一个简单的./
I still got 我还是
Cannot find module './folder2/file2.js'
I really don't understand that 我真的不明白
fs
is unaware of current module path and relies on current working directory ( process.cwd()
) for relative paths. fs
不知道当前的模块路径,并且依赖于当前工作目录( process.cwd()
)的相对路径。
For actions that are specific to current module path, __dirname
should be used: 对于特定于当前模块路径的操作,应使用__dirname
:
fs.readdirSync(path.join(__dirname, '../folder2'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.