sync.cjs 912 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. const path = require('path');
  3. const {readFileSync} = require('fs');
  4. const isNodeModules = require('./is-node-modules.cjs');
  5. const resultsCache = require('./cache.cjs');
  6. function getDirectoryTypeActual(directory) {
  7. if (isNodeModules(directory)) {
  8. return 'commonjs';
  9. }
  10. try {
  11. return JSON.parse(readFileSync(path.resolve(directory, 'package.json'))).type || 'commonjs';
  12. } catch (_) {
  13. }
  14. const parent = path.dirname(directory);
  15. if (parent === directory) {
  16. return 'commonjs';
  17. }
  18. return getDirectoryType(parent);
  19. }
  20. function getDirectoryType(directory) {
  21. if (resultsCache.has(directory)) {
  22. return resultsCache.get(directory);
  23. }
  24. const result = getDirectoryTypeActual(directory);
  25. resultsCache.set(directory, result);
  26. return result;
  27. }
  28. function getPackageTypeSync(filename) {
  29. return getDirectoryType(path.resolve(path.dirname(filename)));
  30. }
  31. module.exports = getPackageTypeSync;