/** * 保存字符串为文本文件 */ const path = require('path') const fs = require('fs') const projectRoot = path.resolve(__dirname, '..', '..', '..') /** 构建绝对路径:绝对路径直接返回,否则相对于 folderPath 或项目根 */ function buildFilePath(filePath, folderPath) { if (filePath.startsWith('/') || filePath.includes(':')) return filePath return folderPath ? path.join(folderPath, filePath) : filePath } function writeTextFile(filePath, content) { const fullPath = path.isAbsolute(filePath) ? filePath : path.resolve(projectRoot, filePath) const dir = path.dirname(fullPath) if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }) fs.writeFileSync(fullPath, content) return { success: true } } /** 执行保存文本文件 */ async function executeSaveTxt({ filePath, content, folderPath }) { if (!filePath) return { success: false, error: 'save-txt 缺少 filePath 参数' } if (content === undefined || content === null) return { success: false, error: 'save-txt 缺少 content 参数' } const absoluteFilePath = buildFilePath(filePath, folderPath) const contentStr = typeof content === 'string' ? content : String(content) writeTextFile(absoluteFilePath, contentStr) return { success: true } } module.exports = { executeSaveTxt, writeTextFile }