Naimur
Naimur

Reputation: 21

Making directories in Node js at depth

I am trying to achieve this

Write a script (in any language) that accepts a single parameter (depth) to create the expected folders and files:

  1. At depth 0, create a folder named 0, and create a file in it with its relative path as the content.
  2. At depth 1: besides what should be done with depth 0, create two subfolders named 0 and 1 and create a file to save its path in both respectively.
  3. At depth 2: besides what should be done at depth 1, create subfolders in folders created at depth 1, and name them as 0, 1 and 2, and create files following the same rule.
  4. At depth N: Same rules.

I tried this way,

const fs = require('fs');

function makedir(depth) {
    let newpath = [];
    for (let i = 0; i <= depth; i++) {
        newpath.push(i);
        let joined = newpath.join('/');
        if (!fs.existsSync(joined)) {
            fs.mkdirSync(joined);
            fs.writeFileSync('path.txt', joined);
        }
    }
}
makedir(2);

But it failed to do the job.
It only created folders like this 0/1/2 and a file only in the root directory

Upvotes: 1

Views: 508

Answers (2)

Duy Quoc
Duy Quoc

Reputation: 181

You can use recursion and path module [optional] to resolve:

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

// set curPath = __dirname if you want to use absolute path
function makeDir(depth, index = 0, curPath = './') { 
  if (index >= depth) {
    return;
  } else {
    let numFold = index;
    do {
      const relativePath = path.join(curPath, `${numFold}`);
      fs.mkdirSync(relativePath, { recursive: true });
      fs.writeFileSync(path.join(relativePath, 'path.txt'), relativePath);
      makeDir(depth, index + 1, relativePath);
      numFold--;
    } while (numFold >= 0);
  }
}

makeDir(5);

Explanations

  • Use recursion to create nested directories.
  • Use a do-while loop to generate the number of directories at each depth.
  • Use path.join This function takes a variable number of arguments, joins them together, and normalizes the path.

Upvotes: 1

Krishna Kokatay
Krishna Kokatay

Reputation: 36

Worked on this solution for a few hours. It's very unoptimized, but it works from mkdir(0) to mkdir(6). I'm sure that my code can be improved upon!

The function takes the lowest depth, generates all possible unique permutations from that number, removes any numbers that don't fit the tree like hierarchy, then generates folders and files according to that number. The process is then repeated for higher and higher depths.

If you can find a way to generate the list of paths from the ground up, without calculating all permutations, that would greatly improve performance.

const fs = require('fs');

function mkdir(depth) {
    for (h=0; h<=depth; h++) {
        let x = ""
        for (i=0; i <= h; i++) {
            x += i.toString()
        }
        x = x.split('')
        x = allPossibleCombinations(x, (h + 1), '');
        for (i=(x.length - 1); i >= 0; i--) {
            nlength = x[i].toString().length - 1
            for (j=0; j < nlength; j++) {
                if (Number(x[i][j]) > j && x[i] !== " ") {
                    x.splice(i, 1, " ")
                }
            }
        }
        x = x.filter(function(value, index, arr) {
            if (value !== " ") {
                return value;
            }
        })
        for (i=0; i < x.length; i++) {
            let targetDir = "./" + x[i].match(/.{1}/g).join("/") + "/";
            if (!fs.existsSync(targetDir)) {
                fs.mkdirSync(targetDir, { recursive: true });
            }
            if (!fs.existsSync(targetDir + "path.txt")) {
                fs.writeFileSync(targetDir + 'path.txt', targetDir);
            }
        }
    }
}

function allPossibleCombinations(input, length, curstr) {
    if(curstr.length == length) return [ curstr ];
    var ret = [];
    for(var i = 0; i < input.length; i++) {
        ret.push.apply(ret, allPossibleCombinations(input, length, curstr + input[i]));
    }
    return ret;
}

mkdir(6);

Upvotes: 1

Related Questions