1/* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import fs, { constants, Stats } from 'fs'; 17import path from 'path'; 18import { LogUtil } from './logUtil'; 19 20export class FileUtils { 21 static readFileContent(file: string): string | undefined { 22 return fs.readFileSync(file, 'utf-8'); 23 } 24 25 static readFilesInDir(dirName: string, filter?: (name: string) => boolean): Array<string> { 26 const files: Array<string> = []; 27 fs.readdirSync(dirName, { withFileTypes: true }).forEach((dir) => { 28 const filePath = path.join(dirName, dir.name); 29 if (dir.isFile()) { 30 if (!filter) { 31 files.push(filePath); 32 return; 33 } 34 if (filter(dir.name)) { 35 files.push(filePath); 36 } 37 return; 38 } 39 files.push(...FileUtils.readFilesInDir(filePath, filter)); 40 }); 41 return files; 42 } 43 44 static writeStringToFile(str: string, filePath: string): void { 45 const parentDir = path.dirname(filePath); 46 if (!FileUtils.isExists(parentDir)) { 47 fs.mkdirSync(parentDir, { recursive: true }); 48 } 49 fs.writeFileSync(filePath, str); 50 } 51 52 static isDirectory(path: string): boolean { 53 const stats: Stats = fs.lstatSync(path); 54 return stats.isDirectory(); 55 } 56 57 static isExists(path: string | undefined): boolean { 58 if (!path) { 59 return false; 60 } 61 try { 62 fs.accessSync(path, constants.R_OK); 63 return true; 64 } catch (exception) { 65 return false; 66 } 67 } 68 69 static getFileTimeStamp(): string { 70 const now = new Date(); 71 return `${now.getFullYear()}_${now.getMonth() + 1}_${now.getDate()}_${now.getHours()}_${now.getMinutes()}_${now.getSeconds()}`; 72 } 73}