save-txt.js 2.9 KB

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