import * as path from 'path'; import * as http from 'https'; import * as fs from "fs"; /** * 下载文件到指定的文件地址 */ export function downLoadFile(url: string, filePath: string) { if (fs.existsSync(filePath)) fs.unlinkSync(filePath); else if (!fs.existsSync(path.dirname(filePath))) fs.mkdirSync(path.dirname(filePath)); let file = fs.createWriteStream(filePath); http.get(url, function (response) { response.pipe(file); }); } /** * 拷贝文件. * * @param {*} source 目标文件的地址 * @param {*} targetFile 拷贝到新的地址 */ export function copyFileSync(source: string, targetFile: string) { //if target is a directory a new file with the same name will be created if (fs.existsSync(targetFile)) { if (fs.lstatSync(targetFile).isDirectory()) targetFile = path.join(targetFile, path.basename(source)); } fs.writeFileSync(targetFile, fs.readFileSync(source)); console.log('targetFile: ', targetFile); } export function copyFolderRecursiveSync(source: string, target: string) { let files: string[] = []; //check if folder needs to be created or integrated let targetFolder = path.join(target, path.basename(source)); if (!fs.existsSync(targetFolder)) fs.mkdirSync(targetFolder); //copy if (fs.lstatSync(source).isDirectory()) { files = fs.readdirSync(source); files.forEach(function (file) { let curSource = path.join(source, file); if (fs.lstatSync(curSource).isDirectory()) copyFolderRecursiveSync(curSource, targetFolder); else copyFileSync(curSource, targetFolder); }); } } /** * 获得文件夹内所有的文件(递归遍历) */ export function getFiles(path: string, resultFiles: string[] = []) { let files = fs.readdirSync(path); for (let file of files) { let name = path + '/' + file; if (fs.statSync(name).isDirectory()) getFiles(name, resultFiles); else resultFiles.push(name); } return resultFiles; }