我正努力实现这一目标
编写接受单个参数(深度)以创建预期文件夹和文件的脚本(任何语言):
我试过这样做,
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);但它没能做好这份工作。
它只创建了类似0/1/2的文件夹,并且只在根目录中创建了一个文件
发布于 2021-06-02 12:18:12
研究了几个小时的解决方案。它非常没有优化,但是从mkdir(0)到mkdir(6)都能工作。我确信我的代码是可以改进的!
该函数的深度最低,从该数字生成所有可能的唯一排列,删除任何不符合树的层次结构的数字,然后根据该数字生成文件夹和文件。然后,这个过程在更高的深度重复进行。
如果您能够找到一种从底层生成路径列表的方法,而无需计算所有排列,这将极大地提高性能。
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);发布于 2021-06-02 15:22:18
您可以使用递归和路径模块进行可选的解析:
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);解释
do-while循环生成每个深度的目录数。path.join --此函数接受可变数量的参数,将它们连接在一起,并使路径正常化。https://stackoverflow.com/questions/67801541
复制相似问题