0

I'm using Node.js and want to split my code into separate files. However, it seems quite verbose to require these modules in a reliable way.

For example:

var module = require(path.resolve(__dirname, "./file.js"));

Furthermore, if the file is in a different folder, I'll need to deal with relative path mayhem.

It seems like quite a simple problem, but my research hasn't yielded a solution. Thanks for you time.

Luke
  • 2,038
  • 3
  • 22
  • 46
  • Why are relative paths unreliable? I've never run into an issue coding the relative path... `const module = require('../other_folder/file.js')` – TJBlackman Apr 25 '18 at 00:51
  • @TJBlackman It is reliable, just very verbose. Without `path.resolve` and `__dirname`, you have to guarantee that the user is running the script in the correct folder. Relative paths can be annoying if you have a large tree, however. – Luke Apr 25 '18 at 00:54
  • 3
    @iONinja Relative paths (if they begin with `./`) are resolved _relative to the file they appear in._ The code shown in your question should behave identically to `var module = require('./file.js');` in all common cases. – cdhowie Apr 25 '18 at 00:56
  • @cdhowie, [thanks](https://stackoverflow.com/a/50012690/5583289). – Luke Apr 25 '18 at 01:14
  • 1
    @iONinja No problem. Note that this is _not_ the case for "bare" paths, as in `require('file.js')`, which will only search the include folders (typically includes `node_modules` up the directory tree). `./` is the magic bit that tells `require()` that you want it to look relative to the directory containing the current module (and _only_ that directory -- include directories aren't searched). – cdhowie Apr 25 '18 at 01:17

1 Answers1

0

Require paths are always relative to the script being run, so you don't need path.resolve or __dirname.

There are a number of solutions for avoiding the inconvenience of relative paths.

Thanks cdhowie for your comment.

Luke
  • 2,038
  • 3
  • 22
  • 46