const fs = require ( 'fs' )
const path = require ( 'path' )
const getPath = ( url ) => {
return path. join ( __dirname, url)
}
function parseArgv ( ) {
let arguments = process. argv. splice ( 2 )
const target = arguments[ 0 ] || './copy'
const source = arguments[ 1 ] || './'
return { target, source }
}
const isDir = ( pathDir ) => {
const path = getPath ( pathDir)
let data = false
try {
data = fs. statSync ( path) . isDirectory ( )
return data
} catch ( error) {
return data
}
}
const getDirList = ( pathDir ) => {
const path = getPath ( pathDir)
return new Promise ( ( resolve, reject ) => {
fs. readdir ( path, ( err, data ) => {
if ( err) {
rejects ( err)
}
resolve ( data)
} )
} )
}
const exclude = [ 'node_modules' , '.gitignore' ]
const main = async ( target, source ) => {
let list = await getDirList ( source)
const except = [ path. basename ( target) , path. parse ( __filename) . base]
list = list. filter ( ( item ) => {
return ! except. includes ( item)
} )
isDir ( target) ? '' : fs. mkdirSync ( target, { recursive : true } )
const copyFile = ( list, target, source ) => {
list. forEach ( async ( item ) => {
const path =
source. endsWith ( './' ) || source. endsWith ( '/' )
? './' + item
: source + '/' + item
const copyPath = target + '/' + item
if ( isDir ( path) ) {
if ( ! fs. existsSync ( copyPath) ) {
await fs. mkdirSync ( copyPath)
console. log ( ` 正在创建:文件夹从 ${ getPath ( path) } ------->创建到 ${ getPath ( copyPath) } ======成功 ` )
}
let needCopyList = await getDirList ( path)
needCopyList = needCopyList. filter ( ( item ) => {
return ! exclude. includes ( item)
} )
await copyFile ( needCopyList, copyPath, path)
} else {
if ( ! fs. existsSync ( copyPath) ) {
fs. copyFileSync ( path, copyPath)
console. log ( ` 正在复制:文件从 ${ getPath ( path) } ------->复制到 ${ getPath ( copyPath) } ======成功 ` )
}
}
} )
}
copyFile ( list, target, source)
}
const { target, source } = parseArgv ( )
main ( target, source)