save-txt.js 1.1 KB

1234567891011121314151617181920212223242526272829
  1. /**
  2. * 保存字符串为文本文件
  3. */
  4. const path = require('path')
  5. const fs = require('fs')
  6. /** 构建绝对路径:绝对路径直接返回,否则相对于 folderPath 或项目根 */
  7. function buildFilePath(filePath, folderPath) {
  8. if (filePath.startsWith('/') || filePath.includes(':')) return filePath
  9. return folderPath ? path.join(folderPath, filePath) : filePath
  10. }
  11. /** 写入文本文件(供 ef-compiler 调用) */
  12. function writeTextFile(absoluteFilePath, contentStr) {
  13. fs.writeFileSync(absoluteFilePath, contentStr, 'utf8')
  14. }
  15. /** 执行保存文本文件 */
  16. async function executeSaveTxt({ filePath, content, folderPath }) {
  17. if (!filePath) return { success: false, error: 'save-txt 缺少 filePath 参数' }
  18. if (content === undefined || content === null) return { success: false, error: 'save-txt 缺少 content 参数' }
  19. const absoluteFilePath = buildFilePath(filePath, folderPath)
  20. const contentStr = typeof content === 'string' ? content : String(content)
  21. writeTextFile(absoluteFilePath, contentStr)
  22. return { success: true }
  23. }
  24. module.exports = { executeSaveTxt, writeTextFile }