Webpack makes things awkward
As a supplement to all the other already existing solutions:
First things first: If you base the paths of your files and directories on the cwd
(current working directory), things should work as usual, as the cwd
is the folder where you were when you started node
(or npm start
, yarn run
etc).
However...
If you are using webpack, __dirname
behavior will be very different, depending on your node.__dirname
settings, and your webpack version:
- In Webpack v4, the default behavior for
__dirname
is just /
, as documented here.
- In Webpack v5, per the documentation here, the default is already for
__filename
and __dirname
to behave as-is but for the output file, thereby achieving the same result as the config change for v4.
Example
For example, let's say:
- you want to add the static
public
folder
- it is located next to your output (usually
dist
) folder, and you have no sub-folders in dist
, it's probably going to look like this
const ServerRoot = path.resolve(__dirname /** dist */, '..');
// ...
app.use(express.static(path.join(ServerRoot, 'public'))
(important: again, this is independent of where your source file is, only looks at where your output files are!)
More advanced Webpack scenarios
Things get more complicated if you have multiple entry points in different output directories, as the __dirname
for the same file might be different for output file (that is each file in entry
), depending on the location of the output file that this source file was merged into, and what's worse, the same source file might be merged into multiple different output files.
You probably want to avoid this kind of scenario scenario, or, if you cannot avoid it, use Webpack to manage and infuse the correct paths for you, possibly via the DefinePlugin
or the EnvironmentPlugin
.