Source

adminjs/src/utils/file-resolver.ts

  1. import path from 'path'
  2. /**
  3. * resolve relative file path to absolute file path.
  4. * @param filePath relative file path
  5. * @param syntax syntax that match the stack
  6. */
  7. export const relativeFilePathResolver = (filePath: string, syntax: RegExp): string => {
  8. const stack = (new Error().stack || '').split('\n')
  9. const target = stack.findIndex(s => syntax.test(s))
  10. // Node = 8 shows stack like that: '(/path/to/file.ts:77:27)
  11. const pathNode8 = stack[target + 1].match(/\((.*):[0-9]+:[0-9]+\)/)
  12. // Node >= 10 shows stack like that: 'at /path/to/file.ts:77:27
  13. const pathNode10 = stack[target + 1].match(/at (.*):[0-9]+:[0-9]+/)
  14. if (!pathNode8 && !pathNode10) {
  15. throw new Error('STACK does not have a file url. Check out if the node version >= 8')
  16. }
  17. const executionPath = (pathNode8 && pathNode8[1]) || (pathNode10 && pathNode10[1])
  18. return path.join(path.dirname(executionPath as string), filePath)
  19. }