'How can you create multiple directories with paths received in response from from api call?

I am receiving a list of objects from the front-end and i want to create multiple directories from the values stored in that key value pairs. So far I tried this method but it isn't working.

filercv=layerorder.map(layer=>{
    return `layers/${layer.name}`;
  })
  console.log(filercv)

var count 
function makeAllDirs(root, list) {

    return list.reduce((p, item) => {
        return p.then(() => {
          console.log(item)
          console.log(root)
          
            return mkdirp(path.join(root,item));
        });
    }, Promise.resolve());
}

// usage



makeAllDirs(basePath,filercv).then(() => {
   console.log('yes')
}).catch(err => {
   // error here
   console.log(err)
});
};
//layerorder
layerorder=[{"name":"bodies"},{"name":"Top"}]

But when i run this code only one folder is created in the layers directory i.e bodies.



Solution 1:[1]

check within mkdirp(), maybe your path resolves to somewhere else, so check the final constructed path, or maybe the recursive flag is missing: fs.mkdir(path)

Also, try async/await, this will create folders in process.cwd():

const fs = require('fs');
const path = require('path');


function mkdirp(dir) {
    return new Promise((resolve, reject) => {
        console.log('--creating dir: ', path.resolve(dir));
        fs.mkdir(dir, {
            recursive: true
        }, (err) => {
            if (err) reject(err);
            resolve();
        });
    });
}


//layerorder
const layerorder = [{
    "name": "bodies"
}, {
    "name": "Top"
}];

const filercv = layerorder.map(layer => {
    return `layers/${layer.name}`;
});

console.log('dirs: ', filercv);

// check path
let basePath = process.cwd();

async function makeAllDirs() {
    try {
        await Promise.all(filercv.map(dir => {
            console.log(`root: ${basePath}, item: ${dir}`);
            return mkdirp(path.join(basePath, dir))
        }));
        console.log('yes');
    } catch (err) {
        console.log('no', err);
    }
}

makeAllDirs();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 traynor