module-migration-tool
Version:
分析项目文件依赖并迁移到新项目的工具
97 lines (85 loc) • 2.33 kB
JavaScript
/**
* 文件操作相关工具函数
*/
const fs = require("fs")
const path = require("path")
const glob = require("glob")
/**
* 确保目录存在,不存在则创建
* @param {string} dirPath - 目录路径
*/
function ensureDirectoryExists(dirPath) {
if (fs.existsSync(dirPath)) {
return
}
fs.mkdirSync(dirPath, { recursive: true })
}
/**
* 复制文件
* @param {string} source - 源文件路径
* @param {string} target - 目标文件路径
*/
function copyFile(source, target) {
try {
// 确保目标目录存在
ensureDirectoryExists(path.dirname(target))
// 复制文件
fs.copyFileSync(source, target)
return true
} catch (error) {
console.error(`复制文件失败: ${source} -> ${target}`, error)
return false
}
}
/**
* 获取指定目录下的所有文件
* @param {string} directory - 目录路径
* @param {Object} options - 选项
* @param {Array<string>} [options.extensions] - 文件扩展名过滤
* @param {Array<string>} [options.ignorePaths] - 要忽略的路径
* @returns {Array<string>} 文件路径数组
*/
function getAllFiles(directory, options = {}) {
const { extensions = [], ignorePaths = [] } = options
// 构建glob模式
let pattern = `${directory}/**/*`
if (extensions.length > 0) {
pattern = `${directory}/**/*{${extensions.join(",")}}`
}
// 构建忽略模式
const ignorePatterns = ignorePaths.map((p) => `${directory}/**/${p}/**`)
// 查找文件
return glob.sync(pattern, {
nodir: true,
ignore: ignorePatterns,
})
}
/**
* 读取文件内容
* @param {string} filePath - 文件路径
* @returns {string} 文件内容
*/
function readFile(filePath) {
try {
return fs.readFileSync(filePath, "utf-8")
} catch (error) {
console.error(`读取文件失败: ${filePath}`, error)
return ""
}
}
/**
* 获取文件相对路径
* @param {string} basePath - 基准路径
* @param {string} filePath - 文件路径
* @returns {string} 相对路径
*/
function getRelativePath(basePath, filePath) {
return path.relative(path.resolve(basePath), path.resolve(filePath))
}
module.exports = {
ensureDirectoryExists,
copyFile,
getAllFiles,
readFile,
getRelativePath,
}