@truenewx/tnxet
Version:
互联网技术解决方案:Electron扩展支持
61 lines (57 loc) • 1.89 kB
text/typescript
import {app} from 'electron';
import path from 'path';
import fs from 'fs';
import {fileURLToPath} from 'url';
/**
* 基于应用路径获取绝对路径
* @param filePath 应用路径
* @return {string} 绝对路径
*/
export function getAbsolutePathBasedOnApp(filePath: string): string {
if (!path.isAbsolute(filePath)) {
filePath = path.join(app.getAppPath(), filePath);
}
return filePath;
}
/**
* 基于相对路径获取绝对路径
* @param filePath 相对路径
* @return {*|string} 绝对路径
*/
export function getAbsolutePathBasedOnRelative(filePath: string): string {
if (!path.isAbsolute(filePath)) {
// 获取当前文件的 URL 并转换为文件系统路径
let filename = fileURLToPath(import.meta.url);
// 获取当前文件所在的目录
let dirname = path.dirname(filename);
// 构建绝对路径
return path.resolve(dirname, filePath);
}
return filePath;
}
export function loopDir(dir: string, pathRegex?: string, consumer?: (filePath: string) => void): boolean {
if (typeof pathRegex === 'function') {
consumer = pathRegex;
pathRegex = undefined;
}
if (fs.statSync(dir).isDirectory()) {
let filenames = fs.readdirSync(dir);
for (let filename of filenames) {
let filePath = path.join(dir, filename);
let stats = fs.statSync(filePath);
if (stats.isDirectory()) {
loopDir(filePath, pathRegex, consumer);
} else if (stats.isFile()) {
if (typeof pathRegex === 'string') {
let regex = new RegExp(pathRegex);
if (!regex.test(filePath)) {
continue;
}
}
consumer(filePath);
}
}
return true;
}
return false;
}