Search code examples
javascriptnode.jsimportpathrequire

How to require a JS file from an external source/directory without path issues?


How do I require another module from a different directory without having path issues?

For example, src/index.js, has a require('../other/main') statement

Oh, there's an error, because in the main.js JS file, there are things like getting files from paths, and it's just a path issue. (e.g. ./SOMEFILE won't work when it's clearly in that other directory path)

But, if I individually on my CLI, to cd other, and npm start (or node main.js), no path issue.

How do I require without having to cd into the directory to make the path work?

But I don't get it, how do I just easily require a JS file but from another directory with a package.json or whatever?


Solution

  • Just use process.chdir(directory) so you don't have path issues. https://nodejs.org/api/process.html#processchdirdirectory

    You can use child_process.fork to make a new process of your external JS script (so it runs). https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options

    We would have to use process.chdir, I cannot find another way.