简体   繁体   中英

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

from file 1 i want to require file2

if I do 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 ./

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.

For actions that are specific to current module path, __dirname should be used:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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