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 } from 'fs'; 17import path from 'path'; 18import { LogUtil } from './logUtil'; 19import type { Stats } from 'fs'; 20 21export class FileUtils { 22 static readFileContent(file: string): string | undefined { 23 return fs.readFileSync(file, 'utf-8'); 24 } 25 26 static readFilesInDir(dirName: string, filter?: (name: string) => boolean): Array<string> { 27 const files: Array<string> = []; 28 fs.readdirSync(dirName, { withFileTypes: true }).forEach((dir) => { 29 const filePath = path.join(dirName, dir.name); 30 if (dir.isFile()) { 31 if (!filter) { 32 files.push(filePath); 33 return; 34 } 35 if (filter(dir.name)) { 36 files.push(filePath); 37 } 38 return; 39 } 40 files.push(...FileUtils.readFilesInDir(filePath, filter)); 41 }); 42 return files; 43 } 44 45 static writeStringToFile(str: string, filePath: string): void { 46 const parentDir = path.dirname(filePath); 47 if (!FileUtils.isExists(parentDir)) { 48 fs.mkdirSync(parentDir, { recursive: true }); 49 } 50 fs.writeFileSync(filePath, str); 51 } 52 53 static isDirectory(path: string): boolean { 54 const stats: Stats = fs.lstatSync(path); 55 return stats.isDirectory(); 56 } 57 58 static isExists(path: string | undefined): boolean { 59 if (!path) { 60 return false; 61 } 62 try { 63 fs.accessSync(path, constants.R_OK); 64 return true; 65 } catch (exception) { 66 return false; 67 } 68 } 69 70 static getFileTimeStamp(): string { 71 const now = new Date(); 72 return `${now.getFullYear()}_${now.getMonth() + 1}_${now.getDate()}_${now.getHours()}_${now.getMinutes()}_${now.getSeconds()}`; 73 } 74}