Skip to content
Advertisement

node.js multiple __dirnames

Can I put more than one file/directory down with __dirname ?
example:
const dirPath = path.join(__dirname, ‘/candles’);
const dirPath = path.join(__dirname, ‘/lightbulbs’);
const dirPath = path.join(__dirname, ‘/flashlights’);
versus some sort of
const dirPath = path.join(__dirname, {‘/pictures’, ‘/lightbulbs’, ‘/flashlights’}); I wish to have a list of files instead of a directory.

Advertisement

Answer

For this question, you should really try what you think will work, then only post a question if it ends up not working and you can’t fix it. Sometimes it doesn’t make sense to do that, but it’s typically going to help provide context to the problem and help people provide higher quality answers.

I’m not sure what you mean by const dirPath = path.join(__dirname, {‘/pictures’, ‘/lightbulbs’, ‘/flashlights’});. That won’t work because path only accepts strings and only returns one path, and it’s an improper use of {} (you probably meant to use []).

Your code here:

const dirPath = path.join(__dirname, ‘/candles’);
const dirPath = path.join(__dirname, ‘/lightbulbs’);
const dirPath = path.join(__dirname, ‘/flashlights’);

is declaring the same variable and will cause an error. But if you named the variables differently, it should be fine.

This is how I would personally go about getting “a list of paths”:

const directories = ['/candles', '/lightbulbs', 'flashlights'];

const paths = directories.map( e => path.join(__dirname, e) );
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement