/** * 读取根目录下的文本文件 * 支持从项目根目录读取文本文件内容 */ const electronAPI = require('../node-api.js') const tagName = 'read-txt' const schema = { description: '读取根目录下的文本文件内容。', inputs: { filePath: '文件路径(相对于项目根目录,如 "config.txt" 或 "data/input.txt")', variable: '输出变量名(保存文件内容)', }, outputs: { variable: '文件内容(字符串)', }, }; /** * 执行读取文本文件 * @param {Object} params - 参数对象 * @param {string} params.filePath - 文件路径(相对于项目根目录) * @param {string} params.folderPath - 工作流文件夹路径(用于构建绝对路径) * @returns {Promise<{success: boolean, error?: string, content?: string}>} */ async function executeReadTxt({ filePath, folderPath }) { try { if (!filePath) { return { success: false, error: 'read-txt 缺少 filePath 参数' }; } if (!electronAPI.readTextFile) { return { success: false, error: '读取文本文件 API 不可用' }; } // 构建文件路径 // 如果 filePath 是绝对路径,直接使用 // 如果提供了 folderPath(工作流目录),相对于工作流目录 // 否则,相对于项目根目录 let absoluteFilePath = filePath; // 如果是相对路径(不以 / 开头且不包含 :) if (!filePath.startsWith('/') && !filePath.includes(':')) { // 如果提供了工作流目录,相对于工作流目录 if (folderPath) { // folderPath 格式可能是:static/processing/微信聊天自动发送工作流 // 需要构建绝对路径 if (folderPath.startsWith('static/processing/')) { const folderName = folderPath.replace('static/processing/', ''); // 构建工作流目录的绝对路径,然后拼接文件路径 // 这里需要调用主进程的 API 来解析路径,或者使用相对路径 // 由于主进程的 readTextFile 只支持相对于项目根目录的路径 // 我们需要构建相对于项目根目录的完整路径 absoluteFilePath = `static/processing/${folderName}/${filePath}`; } else { absoluteFilePath = `${folderPath}/${filePath}`; } } else { // 没有工作流目录,相对于项目根目录 absoluteFilePath = filePath; } } // 调用主进程的 readTextFile API // 主进程会将相对路径解析为相对于项目根目录的绝对路径 // 如果文件不存在,主进程会返回空字符串 const result = electronAPI.readTextFile(absoluteFilePath); // 即使文件不存在,也返回成功(内容为空字符串) if (!result.success) { // 如果读取失败但不是文件不存在的情况,返回错误 return { success: false, error: `读取文件失败: ${result.error}` }; } return { success: true, content: result.content || '' }; } catch (error) { return { success: false, error: error.message || '读取文本文件失败' }; } } module.exports = { tagName, schema, executeReadTxt }