UNPKG

file-manipulator

Version:

## Easy File operations library

82 lines (79 loc) 3.04 kB
import fs from 'fs-extra' const utils = { async checkExist(fullPath: string) { try { return new Promise((ok) => { fs.exists(fullPath, ok) }) } catch (e) { return false } }, async remove(fullPath: string) { try { return new Promise((ok) => { fs.remove(fullPath, (e) => { ok(!e) }) }) } catch (e) { return false } }, async readFile(fullPath: string, encoding: BufferEncoding = 'utf8'): Promise<string> { return await fs.readFile(fullPath, {encoding}) }, async rename(oldFullPath: string, newFullPath: string, overwrite?: boolean) { try { const isSame = oldFullPath === newFullPath if (isSame) return true const isExistBefore = await utils.checkExist(oldFullPath) if (!isExistBefore) return false const isConflictSameName = await utils.checkExist(newFullPath) if (!isConflictSameName) { await fs.rename(oldFullPath, newFullPath) return true } if (isConflictSameName && overwrite) { await utils.remove(newFullPath) await fs.rename(oldFullPath, newFullPath) return true } if (isConflictSameName && !overwrite) return false await fs.rename(oldFullPath, newFullPath) return true } catch (e) { return false } }, async restoreTestFolder() { //remove eache folders inside test folder const isExist1 = await utils.checkExist(`./test_folder/f1`) const isExist2 = await utils.checkExist(`./test_folder/f2`) const isExist3 = await utils.checkExist(`./test_folder/f3`) if (isExist1) await utils.remove(`./test_folder/f1`) if (isExist2) await utils.remove(`./test_folder/f2`) if (isExist3) await utils.remove(`./test_folder/f3`) //rewrite each file in each folder (or create) fs.mkdirpSync(`./test_folder/f1`) fs.mkdirpSync(`./test_folder/f2`) fs.writeFileSync(`./test_folder/f1/f1.txt`, 'test file 1', 'utf8') fs.writeFileSync(`./test_folder/f2/f2.txt`, 'test file 2', 'utf8') console.log('🍎 test folder restored 🍎') }, getNameByConfig(config: { ext?: string, name?: string }): string { const isAlreadyExt = !!config.name && !!config?.ext && config.name.endsWith(config.ext) if (isAlreadyExt) { return config.name || '' } return `${config.name}${!!config?.ext ? ('.' + config.ext) : ('')}` }, getNameRenameConfig(config: { ext?: string, name?: string, renameTo?: string }): string { const newName = !!config?.renameTo ? config?.renameTo : config.name return this.getNameByConfig({name: newName, ext: config.ext}) } } export default utils