It is common seen in webpack configuration that when we need to set the path ,path.resolve
or path.join
are often use
This has nothing to do with webpack, only with the way Node.js handles paths. Paths are not resolved relative to the file path, but relative to the working directory by default. Say we have the following directory structure:
project
├── a
| └── 1.js
└── b
└── 2.txt
with 1.js containing the following:
const filePath = '../b/2.txt';
const content = require('fs').readFileSync(filePath);
console.log(content.toString());
then, if we run
cd a
node 1.js
everything works fine.
But if, instead we execute from the toplevel directory, the following:
node a/1.js
we get an error:
Error: ENOENT: no such file or directory, open 'C:\Users\baryl\Desktop\b\2.txt'
because the path is now resolved relative to project
instead of project/a
. path.resolve solves that.
const path = require('path');
const filePath = path.resolve(__dirname, '../b/2.txt');
const content = require('fs').readFileSync(filePath);
console.log(content.toString());
now we can safely execute node a/1.js
from the project directory, and it will work as expected.