node-创建文件目录

  • 使用 Node 按照传入的 JSON 创建一个目录结构,避免了繁琐的文件创建过程
  • npm - generator-files

node-创建文件目录

希望达到的目的:传入指定格式的 JSON 数据,使用 Node 创建相应的文件夹和文件

JSON 格式

  1. 如果 KEY 不是 files,将使用 KEY 来作为创建文件夹的文件夹名称
  2. 如果 KEY 是 files,其值(数组或者字符串)将作为创建文件的依据

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
{
"src": {
"pages": {
"other": {
"style": {
"css": {
"files": ["other.css"]
},
"scss": {
"files": ["other.scss"]
}
},
"script": {
"js": {
"files": ["other.js"]
}
},
"files": ["other.html", "entry.js"]
}
},
"resource": {
"images": {},
"fonts": {},
"media": {}
},
"style": {
"css": {
"files": ["index.css", "main.css"]
},
"scss": {
"files": ["index.scss", "main.scss"]
}
},
"script": {
"js": {
"files": ["index.js", "main.js"]
}
},
"public": {
"script": {},
"style": {},
"images": {},
"fonts": {},
"media": {}
},
"files": ["index.html", "entry.js"]
},
"files": [
".nvmrc",
"webpack.dev.js",
"webpack.common.js",
"webpack.prod.js"
]
}

创建目录结构

这里使用 yargs 来接受命令行参数

generator_files.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
onst yargs = require("yargs")
const argv = yargs.argv;
const path = require("path");
const fs = require("fs");

yargs.scriptName("generate_files")
.usage('$0 [args]').describe('files', "file JSON path").describe('basepath', "generated file path").help('h').argv;


const dir_structure = argv.files ? require(path.resolve(process.cwd(), argv.files)) : require(path.resolve(__dirname, './lib/files.json'));

const create_dir = path => {
try {
fs.statSync(path, (err, state) => {
if (!state.isDirectory()) {
fs.mkdirSync(path);
}
});
} catch (err) {
fs.mkdirSync(path);
}
};

const create_file = path => {
try {
fs.statSync(path, (err, state) => {
if (!state.isFile()) {
fs.writeFileSync(path, "");
}
});
} catch (err) {
fs.writeFileSync(path, "");
}
};

const create_structure = (structure, base_path) => {
for (const [key, item] of Object.entries(structure)) {
if (key == "files") {
if (Array.isArray(item)) {
item.forEach(v => {
create_file(path.resolve(process.cwd(), base_path + "/" + v));
});
} else if (typeof item === "string") {
create_file(path.resolve(process.cwd(), base_path + "/" + item));
}
} else {
create_dir(path.resolve(process.cwd(), base_path + "/" + key));
create_structure(
item,
path.resolve(process.cwd(), base_path + "/" + key)
);
}
}
fs.writeFileSync(base_path + "/" + ".nvmrc", process.version.slice(1));
};

create_structure(dir_structure, argv.basepath || "./");

使用方式

1
node ./generator_files.js --path=./files_json --basepath=./