save-txt.js 1.3 KB

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