read-txt.js 1.0 KB

123456789101112131415161718192021222324252627282930
  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 readTextFile(filePath) {
  13. const fullPath = path.isAbsolute(filePath) ? filePath : path.resolve(projectRoot, filePath)
  14. const content = fs.readFileSync(fullPath, 'utf8')
  15. return { success: true, content }
  16. }
  17. /** 执行读取文本文件 */
  18. async function executeReadTxt({ filePath, folderPath }) {
  19. if (!filePath) return { success: false, error: 'read-txt 缺少 filePath 参数' }
  20. const absoluteFilePath = buildFilePath(filePath, folderPath)
  21. const result = readTextFile(absoluteFilePath)
  22. return { success: true, content: result.content || '' }
  23. }
  24. module.exports = { executeReadTxt, readTextFile }