save-txt.js 2.9 KB

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