From 7bfdc2cc7c5aa1aaed655c7ddd3a7c3cf38430e5 Mon Sep 17 00:00:00 2001 From: jw255 Date: Sat, 21 Apr 2018 23:01:58 +0100 Subject: implimented moving and copying of files --- src/files.ts | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) (limited to 'src/files.ts') diff --git a/src/files.ts b/src/files.ts index 53360a4..d80f09f 100644 --- a/src/files.ts +++ b/src/files.ts @@ -68,6 +68,10 @@ export const path: (file: string, project: string, view?: ViewName) => string = (file: string, project: string, view: ViewName = 'raw'): string => `${CONTENT_BASE_DIRECTORY}/${project}/${file}/${view}`; +export const pathNoView: (file: string, project: string) => string = + (file: string, project: string): string => + `${CONTENT_BASE_DIRECTORY}/${project}/${file}`; + export const tempPath: (file: string, project: string) => string = ( file: string ): string => @@ -86,7 +90,7 @@ export const saveFile: (filename: string, projectname: string, fileId: string, o let rStream = fs.createReadStream(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); let wStream = fs.createWriteStream(path(fileId, projectname), {'flags':'a'}); rStream.pipe(wStream).on('finish', async() => { - await fs.remove(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); + fs.remove(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); }).on('error', (err: any) => { logger.error(`Error while saving file to proper location: ${err}`); }); @@ -105,6 +109,38 @@ export const truncateFile: (fileId: string, projectName: string, newLength: numb await fs.ftruncate(fd, newLength); } +export const copyFile: (projName: string, fromId: string, toId: string, move?: boolean) + => Promise = async(projName: string, fromId: string, toId: string, move?: boolean): Promise => { + // ensure to path exists + fs.ensureDirSync(pathNoView(toId, projName)); + const fromDir: string = pathNoView(fromId, projName); + const toDir: string = pathNoView(toId, projName); + // loop all views in file + fs.readdir(fromDir, (err: any, files: string[]) => { + if(err){ + logger.error(`Error while copying file: ${err}`); + } else { + files.forEach((file: string, index: number) => { + const fromPathFull = fromDir + "/" + file; + const toPathFull = toDir + "/" + file; + fs.ensureFileSync(toPathFull); + // open streams to transfer data + let rStream = fs.createReadStream(fromPathFull); + let wStream = fs.createWriteStream(toPathFull); + rStream.pipe(wStream).on('finish', async() => { + if(!!move){ + await fs.remove(fromPathFull); + } + console.log(`copy success of file from \'${fromPathFull}\' to \'${toPathFull}\'`) + }).on('error', (err: any) => { + logger.error(`Error while copying file: ${err}`); + }); + }) + } + }); + +} + export const files: { path: (f: string, p: string) => string; writableStream: (f: string, p: string) => fs.WriteStream; -- cgit v1.2.1