file-manipulator
Version:
## Easy File operations library
59 lines (54 loc) • 2.2 kB
text/typescript
import {ManipulatorInterfaceType} from '../types'
import fs from 'fs-extra'
import path from 'path'
import utils from '../utils'
type MoverFileConfig = {
name: string //file name without ext
ext?: string //name without ext
from: string //folder path from copy
to: string //folder path to paste
renameTo?: string //new optional name for once file
replaceExisting?: boolean //replace if there is exist the same file ? (default false)
}
type MoverFolderOutConfig = {
from: string //folder path from copy
to: string //folder path to paste
name: string //name folder
renameTo?: string //new optional name for once folder
replaceExisting?: boolean //replace if there is exist the same file ? (default false)
}
class Mover implements ManipulatorInterfaceType {
async file(config: MoverFileConfig) {
try {
//file names
const startFullName = utils.getNameByConfig(config)
const endFullName = utils.getNameRenameConfig(config)
//file pathes
const startFullPath = path.resolve(config.from, startFullName)
const endFullPath = path.resolve(config.to, endFullName)
//operations
await fs.move(startFullPath, endFullPath, {overwrite: !!config?.replaceExisting})
return true
} catch (e) {
console.log(this.constructor.name, `[${this.file.name}]`, config.name, e)
return false
}
}
async folder(config: MoverFolderOutConfig) {
try {
//file names
const startFullName = `${config.name}`
const endFullName = config?.renameTo ? `${config?.renameTo}` : startFullName
//file pathes
const startFullPath = path.resolve(config.from, startFullName)
const endFullPath = path.resolve(config.to, endFullName)
//operations
await fs.move(startFullPath, endFullPath, {overwrite: !!config?.replaceExisting})
return true
} catch (e) {
console.log(this.constructor.name, `[${this.folder.name}]`, config.name, e)
return false
}
}
}
export default new Mover()