Node-代码段

  • create_file & create_dir
  • 根据 path 创建文件 若缺少文件或者文件夹将自动创建
  • 分析文件路径

Node-代码段

create_file & create_dir

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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, "");
}
};

分析文件路径

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const glob = require("glob");
const path = require("path");

/**
* 分析文件路径,获取 文件名、扩展名、文件路径、文件夹路径
* @param {string} file_path 文件路径
*/
function analysis_path(file_path) {
let files = glob.sync(file_path);
let result = [];
files.forEach((_path) => {
const dirname = path.dirname(_path);
const extname = path.extname(_path);
const basename = path.basename(_path, extname);
const pathname = path.join(dirname, basename);
result.push({
dirname,
extname,
basename,
pathname,
});
});
return result;
}

根据 path 创建文件

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
const fs = require("fs");
const path = require("path");
/**
* 如果文件不存在就创建文件
* @param {string} path 文件路径
*/
function sync_create_file(path) {
let path_detail = path.split("/");
path_detail.pop();

let will_make_path = [];
let root_param = path_detail.shift();
if (root_param) will_make_path.push(root_param);

path_detail.forEach((path) => {
will_make_path.push(path);
create_dir(will_make_path.join("/"));
});
try {
fs.statSync(path, (err, state) => {
if (!state.isFile()) {
fs.writeFileSync(path, "");
}
});
} catch (err) {
fs.writeFileSync(path, "");
}

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