read-txt.js 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * 读取根目录下的文本文件
  3. * 支持从项目根目录读取文本文件内容
  4. */
  5. export const tagName = 'read-txt';
  6. export const schema = {
  7. description: '读取根目录下的文本文件内容。',
  8. inputs: {
  9. filePath: '文件路径(相对于项目根目录,如 "config.txt" 或 "data/input.txt")',
  10. variable: '输出变量名(保存文件内容)',
  11. },
  12. outputs: {
  13. variable: '文件内容(字符串)',
  14. },
  15. };
  16. /**
  17. * 执行读取文本文件
  18. * @param {Object} params - 参数对象
  19. * @param {string} params.filePath - 文件路径(相对于项目根目录)
  20. * @param {string} params.folderPath - 工作流文件夹路径(用于构建绝对路径)
  21. * @returns {Promise<{success: boolean, error?: string, content?: string}>}
  22. */
  23. export async function executeReadTxt({ filePath, folderPath }) {
  24. try {
  25. if (!filePath) {
  26. return { success: false, error: 'read-txt 缺少 filePath 参数' };
  27. }
  28. if (!window.electronAPI || !window.electronAPI.readTextFile) {
  29. return { success: false, error: '读取文本文件 API 不可用' };
  30. }
  31. // 构建文件路径
  32. // 如果 filePath 是绝对路径,直接使用
  33. // 如果提供了 folderPath(工作流目录),相对于工作流目录
  34. // 否则,相对于项目根目录
  35. let absoluteFilePath = filePath;
  36. // 如果是相对路径(不以 / 开头且不包含 :)
  37. if (!filePath.startsWith('/') && !filePath.includes(':')) {
  38. // 如果提供了工作流目录,相对于工作流目录
  39. if (folderPath) {
  40. // folderPath 格式可能是:static/processing/微信聊天自动发送工作流
  41. // 需要构建绝对路径
  42. if (folderPath.startsWith('static/processing/')) {
  43. const folderName = folderPath.replace('static/processing/', '');
  44. // 构建工作流目录的绝对路径,然后拼接文件路径
  45. // 这里需要调用主进程的 API 来解析路径,或者使用相对路径
  46. // 由于主进程的 readTextFile 只支持相对于项目根目录的路径
  47. // 我们需要构建相对于项目根目录的完整路径
  48. absoluteFilePath = `static/processing/${folderName}/${filePath}`;
  49. } else {
  50. absoluteFilePath = `${folderPath}/${filePath}`;
  51. }
  52. } else {
  53. // 没有工作流目录,相对于项目根目录
  54. absoluteFilePath = filePath;
  55. }
  56. }
  57. // 调用主进程的 readTextFile API
  58. // 主进程会将相对路径解析为相对于项目根目录的绝对路径
  59. // 如果文件不存在,主进程会返回空字符串
  60. const result = await window.electronAPI.readTextFile(absoluteFilePath);
  61. // 即使文件不存在,也返回成功(内容为空字符串)
  62. if (!result.success) {
  63. // 如果读取失败但不是文件不存在的情况,返回错误
  64. return { success: false, error: `读取文件失败: ${result.error}` };
  65. }
  66. return {
  67. success: true,
  68. content: result.content || ''
  69. };
  70. } catch (error) {
  71. return { success: false, error: error.message || '读取文本文件失败' };
  72. }
  73. }