Skip to content

Instantly share code, notes, and snippets.

@GUIEEN
Last active January 3, 2019 13:59
Show Gist options
  • Save GUIEEN/a7ee0e01625c4f8ccd1d1bdf6065ea81 to your computer and use it in GitHub Desktop.
Save GUIEEN/a7ee0e01625c4f8ccd1d1bdf6065ea81 to your computer and use it in GitHub Desktop.
Get all files recursively in the specific directory
import path from 'path'
import fs from 'fs'
let targetPath = path.resolve(__dirname, '../')
let files: string[] = []
const ignore = {
'src/copyFolder.ts': true,
'src/starter.ts': true,
'.git': true,
'.gitignore': true,
node_modules: true
}
const recursively = (
targetPath: string,
list: string[] = [],
base: string = ''
): string[] => {
let tmp = fs.readdirSync(targetPath).map(e => path.join('', e))
for (let i = 0; i < tmp.length; i++) {
let currentPath = tmp[i]
if (ignore[currentPath]) {
tmp.splice(i, 1)
i--
continue
}
if (fs.lstatSync(path.join(targetPath, currentPath)).isDirectory()) {
tmp.splice(i, 1)
const tmpLen = tmp.length
tmp = recursively(path.join(targetPath, currentPath), tmp, currentPath)
i = tmp.length > tmpLen ? tmp.length - 1 : i - 1
}
}
list = [...list, ...tmp.map(e => path.join(base, e))]
return list
}
files = recursively(targetPath, [])
// /Users/guieenoutis/Desktop/ts-starter
// [ 'README.md',
// 'package-lock.json',
// 'package.json',
// 'tsconfig.json',
// 'tslint.json',
// 'src/app.ts',
// 'src/configuration.ts',
// 'src/copyFolder.ts',
// 'src/starter.ts' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment