read-txt.js 3.1 KB

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