Search code examples
javascriptnode.jspathrequirefs

Why do do relative paths in Node.js for FS module and require point at different locations?


When we run the server on Node JS we should use paths relative to which directory we launched node in. To solve this issue we ought to use the path module like this:

fs.createReadStream(path.join(__dirname, '..', '..', 'data', 'someData.csv'))

But when we use require we can just place a relative path to the file in which we're requiring, wthout having to consider where node is launched from:

const {data} = require('../../models/data.model');

Can you please explain: why does it work that way?


Solution

  • The fs module handles relative paths relative to the process's working directory, e.g. where it's launched. You can use process.cwd() to figure out where that is.

    When it comes to require, that's a bit of a special case. When your script/module gets initialized and called, NodeJS will under the hood create a brand new require function. You can read more about that here.

    Basically, your module has its own require which knows of __dirname and makes all relative paths passed to it be relative to that path.