Skip to content

Commit

Permalink
refactor: extract common utils
Browse files Browse the repository at this point in the history
  • Loading branch information
w2xi committed Feb 3, 2024
1 parent 44b6554 commit 8b3f956
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 22 deletions.
28 changes: 6 additions & 22 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const fs = require('fs')
const { program } = require('commander')
const { fileExistSync, isDirectory } = require('./utils')
const package = require('../package.json')

const map = {
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
}
})
Expand All @@ -108,23 +102,13 @@ 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) => {
if (err) throw err
})
}

// 检测文件或文件夹是否存在
function fileExistSync(path) {
try {
fs.accessSync(path, fs.constants.F_OK)
} catch(e) {
return false
}
return true
}

console.log(root.name)
console.log(output)
21 changes: 21 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -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,
}

0 comments on commit 8b3f956

Please sign in to comment.