node.js - Node js找不到与父路径相关的我自己的模块

标签 node.js fs

我有一棵这样的树。

folder1
    file1.js
folder2
    file2.js
index.js

我需要使用index.js 中的file1

我想从文件 1 获取文件 2

如果我这样做 const file2= require('../folder2/file2.js'); 它可以工作

如果我动态地这样做

const myFiles = fs.readdirSync('../folder2').filter(file => file.endsWith('.js'));
for (const file of myFiles ) 
{
    const myFile = require(`../folder2/${file}`);
} 

我收到了

 return binding.readdir(pathModule._makeLong(path), options.encoding);
                 ^

Error: ENOENT: no such file or directory, scandir 'displaying a wrong path here'

如果在我的 readdir 中我做了一个简单的 ./

我还有

Cannot find module './folder2/file2.js'

我真的不明白

最佳答案

fs 不知道当前模块路径,并依赖于当前工作目录 (process.cwd()) 的相对路径。

对于特定于当前模块路径的操作,应使用 __dirname:

fs.readdirSync(path.join(__dirname, '../folder2'))

关于node.js - Node js找不到与父路径相关的我自己的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52926924/

相关文章:

node.js - 在 Node 上使用 Cheerio 修改后写入文件

javascript - React Native 上的 git clone 错误如何解决这个问题

javascript - 如何从 Istanbul 尔报道中忽略 node.js 中所需的文件

node.js - 确定 Node js中读取流的长度

javascript - node.js fs.readdir 不显示目录中的任何文件

javascript - Node.JS fs.readFileSync() 错误参数

Node.js 'fs' - 创建文件+清除文件的更有效方式

javascript - 为什么 Meteor.users.findOne({username : "test"}) returns an object but replacing "test" with variable that has the same value returns undefined

node.js - 移动设备上的自动化测试执行

node.js - 需要 ('../' ) 是什么意思?