diff --git a/src/index.js b/src/index.js index b2eae41..1d38bea 100644 --- a/src/index.js +++ b/src/index.js @@ -2,6 +2,7 @@ const fs = require('fs') const { program } = require('commander') +const { fileExistSync, isDirectory } = require('./utils') const package = require('../package.json') const map = { @@ -38,19 +39,14 @@ if (options.ignore) { // https://stackoverflow.com/questions/32478698/what-is-the-different-between-stat-fstat-and-lstat-functions-in-node-js function toTree(path, deep = 0) { - const stats = fs.lstatSync(path) - - if (stats.isDirectory()) { + if (isDirectory(path)) { let dir = fs.readdirSync(path) if (ignoreList.length) { dir = dir.filter(child => !ignoreList.includes(child)) } if (options.onlyFolder) { - dir = dir.filter(child => { - const childStats = fs.lstatSync(`${path}/${child}`) - return childStats.isDirectory() - }) + dir = dir.filter(child => isDirectory(`${path}/${child}`)) } const children = dir.map(child => toTree(`${path}/${child}`, deep + 1)) const dirName = path.split('/').pop() @@ -93,12 +89,10 @@ function generateTreeStructure(data, deep = 0) { currentLineStr += '\n' - if (item.children) { - // 目录 + if (item.children) { // directory output += currentLineStr generateTreeStructure(item.children, deep + 1) - } else { - // 文件 + } else { // file output += currentLineStr } }) @@ -108,7 +102,7 @@ generateTreeStructure(root.children) if (options.output) { let outputString = output - if (fileExistSync(options.output)) { // 追加处理 + if (fileExistSync(options.output)) { // appending mode outputString = '\n' + output } fs.appendFile(options.output, outputString, (err) => { @@ -116,15 +110,5 @@ if (options.output) { }) } -// 检测文件或文件夹是否存在 -function fileExistSync(path) { - try { - fs.accessSync(path, fs.constants.F_OK) - } catch(e) { - return false - } - return true -} - console.log(root.name) console.log(output) \ No newline at end of file diff --git a/src/utils.js b/src/utils.js new file mode 100644 index 0000000..82256f4 --- /dev/null +++ b/src/utils.js @@ -0,0 +1,21 @@ +const fs = require('fs') + +// check if a file or directory exists. +function fileExistSync(path) { + try { + fs.accessSync(path, fs.constants.F_OK) + } catch(e) { + return false + } + return true +} + +function isDirectory(path) { + const stats = fs.lstatSync(path) + return stats.isDirectory() +} + +module.exports = { + fileExistSync, + isDirectory, +} \ No newline at end of file