You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

301 lines
11 KiB

2 years ago
  1. # resolve <sup>[![Version Badge][2]][1]</sup>
  2. implements the [node `require.resolve()` algorithm](https://nodejs.org/api/modules.html#modules_all_together) such that you can `require.resolve()` on behalf of a file asynchronously and synchronously
  3. [![github actions][actions-image]][actions-url]
  4. [![coverage][codecov-image]][codecov-url]
  5. [![dependency status][5]][6]
  6. [![dev dependency status][7]][8]
  7. [![License][license-image]][license-url]
  8. [![Downloads][downloads-image]][downloads-url]
  9. [![npm badge][11]][1]
  10. # example
  11. asynchronously resolve:
  12. ```js
  13. var resolve = require('resolve/async'); // or, require('resolve')
  14. resolve('tap', { basedir: __dirname }, function (err, res) {
  15. if (err) console.error(err);
  16. else console.log(res);
  17. });
  18. ```
  19. ```
  20. $ node example/async.js
  21. /home/substack/projects/node-resolve/node_modules/tap/lib/main.js
  22. ```
  23. synchronously resolve:
  24. ```js
  25. var resolve = require('resolve/sync'); // or, `require('resolve').sync
  26. var res = resolve('tap', { basedir: __dirname });
  27. console.log(res);
  28. ```
  29. ```
  30. $ node example/sync.js
  31. /home/substack/projects/node-resolve/node_modules/tap/lib/main.js
  32. ```
  33. # methods
  34. ```js
  35. var resolve = require('resolve');
  36. var async = require('resolve/async');
  37. var sync = require('resolve/sync');
  38. ```
  39. For both the synchronous and asynchronous methods, errors may have any of the following `err.code` values:
  40. - `MODULE_NOT_FOUND`: the given path string (`id`) could not be resolved to a module
  41. - `INVALID_BASEDIR`: the specified `opts.basedir` doesn't exist, or is not a directory
  42. - `INVALID_PACKAGE_MAIN`: a `package.json` was encountered with an invalid `main` property (eg. not a string)
  43. ## resolve(id, opts={}, cb)
  44. Asynchronously resolve the module path string `id` into `cb(err, res [, pkg])`, where `pkg` (if defined) is the data from `package.json`.
  45. options are:
  46. * opts.basedir - directory to begin resolving from
  47. * opts.package - `package.json` data applicable to the module being loaded
  48. * opts.extensions - array of file extensions to search in order
  49. * opts.includeCoreModules - set to `false` to exclude node core modules (e.g. `fs`) from the search
  50. * opts.readFile - how to read files asynchronously
  51. * opts.isFile - function to asynchronously test whether a file exists
  52. * opts.isDirectory - function to asynchronously test whether a file exists and is a directory
  53. * opts.realpath - function to asynchronously resolve a potential symlink to its real path
  54. * `opts.readPackage(readFile, pkgfile, cb)` - function to asynchronously read and parse a package.json file
  55. * readFile - the passed `opts.readFile` or `fs.readFile` if not specified
  56. * pkgfile - path to package.json
  57. * cb - callback
  58. * `opts.packageFilter(pkg, pkgfile, dir)` - transform the parsed package.json contents before looking at the "main" field
  59. * pkg - package data
  60. * pkgfile - path to package.json
  61. * dir - directory that contains package.json
  62. * `opts.pathFilter(pkg, path, relativePath)` - transform a path within a package
  63. * pkg - package data
  64. * path - the path being resolved
  65. * relativePath - the path relative from the package.json location
  66. * returns - a relative path that will be joined from the package.json location
  67. * opts.paths - require.paths array to use if nothing is found on the normal `node_modules` recursive walk (probably don't use this)
  68. For advanced users, `paths` can also be a `opts.paths(request, start, opts)` function
  69. * request - the import specifier being resolved
  70. * start - lookup path
  71. * getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution
  72. * opts - the resolution options
  73. * `opts.packageIterator(request, start, opts)` - return the list of candidate paths where the packages sources may be found (probably don't use this)
  74. * request - the import specifier being resolved
  75. * start - lookup path
  76. * getPackageCandidates - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution
  77. * opts - the resolution options
  78. * opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: `"node_modules"`
  79. * opts.preserveSymlinks - if true, doesn't resolve `basedir` to real path before resolving.
  80. This is the way Node resolves dependencies when executed with the [--preserve-symlinks](https://nodejs.org/api/all.html#cli_preserve_symlinks) flag.
  81. **Note:** this property is currently `true` by default but it will be changed to
  82. `false` in the next major version because *Node's resolution algorithm does not preserve symlinks by default*.
  83. default `opts` values:
  84. ```js
  85. {
  86. paths: [],
  87. basedir: __dirname,
  88. extensions: ['.js'],
  89. includeCoreModules: true,
  90. readFile: fs.readFile,
  91. isFile: function isFile(file, cb) {
  92. fs.stat(file, function (err, stat) {
  93. if (!err) {
  94. return cb(null, stat.isFile() || stat.isFIFO());
  95. }
  96. if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
  97. return cb(err);
  98. });
  99. },
  100. isDirectory: function isDirectory(dir, cb) {
  101. fs.stat(dir, function (err, stat) {
  102. if (!err) {
  103. return cb(null, stat.isDirectory());
  104. }
  105. if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
  106. return cb(err);
  107. });
  108. },
  109. realpath: function realpath(file, cb) {
  110. var realpath = typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath;
  111. realpath(file, function (realPathErr, realPath) {
  112. if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr);
  113. else cb(null, realPathErr ? file : realPath);
  114. });
  115. },
  116. readPackage: function defaultReadPackage(readFile, pkgfile, cb) {
  117. readFile(pkgfile, function (readFileErr, body) {
  118. if (readFileErr) cb(readFileErr);
  119. else {
  120. try {
  121. var pkg = JSON.parse(body);
  122. cb(null, pkg);
  123. } catch (jsonErr) {
  124. cb(null);
  125. }
  126. }
  127. });
  128. },
  129. moduleDirectory: 'node_modules',
  130. preserveSymlinks: true
  131. }
  132. ```
  133. ## resolve.sync(id, opts)
  134. Synchronously resolve the module path string `id`, returning the result and
  135. throwing an error when `id` can't be resolved.
  136. options are:
  137. * opts.basedir - directory to begin resolving from
  138. * opts.extensions - array of file extensions to search in order
  139. * opts.includeCoreModules - set to `false` to exclude node core modules (e.g. `fs`) from the search
  140. * opts.readFileSync - how to read files synchronously
  141. * opts.isFile - function to synchronously test whether a file exists
  142. * opts.isDirectory - function to synchronously test whether a file exists and is a directory
  143. * opts.realpathSync - function to synchronously resolve a potential symlink to its real path
  144. * `opts.readPackageSync(readFileSync, pkgfile)` - function to synchronously read and parse a package.json file
  145. * readFileSync - the passed `opts.readFileSync` or `fs.readFileSync` if not specified
  146. * pkgfile - path to package.json
  147. * `opts.packageFilter(pkg, dir)` - transform the parsed package.json contents before looking at the "main" field
  148. * pkg - package data
  149. * dir - directory that contains package.json (Note: the second argument will change to "pkgfile" in v2)
  150. * `opts.pathFilter(pkg, path, relativePath)` - transform a path within a package
  151. * pkg - package data
  152. * path - the path being resolved
  153. * relativePath - the path relative from the package.json location
  154. * returns - a relative path that will be joined from the package.json location
  155. * opts.paths - require.paths array to use if nothing is found on the normal `node_modules` recursive walk (probably don't use this)
  156. For advanced users, `paths` can also be a `opts.paths(request, start, opts)` function
  157. * request - the import specifier being resolved
  158. * start - lookup path
  159. * getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution
  160. * opts - the resolution options
  161. * `opts.packageIterator(request, start, opts)` - return the list of candidate paths where the packages sources may be found (probably don't use this)
  162. * request - the import specifier being resolved
  163. * start - lookup path
  164. * getPackageCandidates - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution
  165. * opts - the resolution options
  166. * opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: `"node_modules"`
  167. * opts.preserveSymlinks - if true, doesn't resolve `basedir` to real path before resolving.
  168. This is the way Node resolves dependencies when executed with the [--preserve-symlinks](https://nodejs.org/api/all.html#cli_preserve_symlinks) flag.
  169. **Note:** this property is currently `true` by default but it will be changed to
  170. `false` in the next major version because *Node's resolution algorithm does not preserve symlinks by default*.
  171. default `opts` values:
  172. ```js
  173. {
  174. paths: [],
  175. basedir: __dirname,
  176. extensions: ['.js'],
  177. includeCoreModules: true,
  178. readFileSync: fs.readFileSync,
  179. isFile: function isFile(file) {
  180. try {
  181. var stat = fs.statSync(file);
  182. } catch (e) {
  183. if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
  184. throw e;
  185. }
  186. return stat.isFile() || stat.isFIFO();
  187. },
  188. isDirectory: function isDirectory(dir) {
  189. try {
  190. var stat = fs.statSync(dir);
  191. } catch (e) {
  192. if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
  193. throw e;
  194. }
  195. return stat.isDirectory();
  196. },
  197. realpathSync: function realpathSync(file) {
  198. try {
  199. var realpath = typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync;
  200. return realpath(file);
  201. } catch (realPathErr) {
  202. if (realPathErr.code !== 'ENOENT') {
  203. throw realPathErr;
  204. }
  205. }
  206. return file;
  207. },
  208. readPackageSync: function defaultReadPackageSync(readFileSync, pkgfile) {
  209. var body = readFileSync(pkgfile);
  210. try {
  211. var pkg = JSON.parse(body);
  212. return pkg;
  213. } catch (jsonErr) {}
  214. },
  215. moduleDirectory: 'node_modules',
  216. preserveSymlinks: true
  217. }
  218. ```
  219. # install
  220. With [npm](https://npmjs.org) do:
  221. ```sh
  222. npm install resolve
  223. ```
  224. # license
  225. MIT
  226. [1]: https://npmjs.org/package/resolve
  227. [2]: https://versionbadg.es/browserify/resolve.svg
  228. [5]: https://david-dm.org/browserify/resolve.svg
  229. [6]: https://david-dm.org/browserify/resolve
  230. [7]: https://david-dm.org/browserify/resolve/dev-status.svg
  231. [8]: https://david-dm.org/browserify/resolve#info=devDependencies
  232. [11]: https://nodei.co/npm/resolve.png?downloads=true&stars=true
  233. [license-image]: https://img.shields.io/npm/l/resolve.svg
  234. [license-url]: LICENSE
  235. [downloads-image]: https://img.shields.io/npm/dm/resolve.svg
  236. [downloads-url]: https://npm-stat.com/charts.html?package=resolve
  237. [codecov-image]: https://codecov.io/gh/browserify/resolve/branch/main/graphs/badge.svg
  238. [codecov-url]: https://app.codecov.io/gh/browserify/resolve/
  239. [actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/browserify/resolve
  240. [actions-url]: https://github.com/browserify/resolve/actions