Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require local node modules with absolute paths doesn't work on Windows

I'm developing a Node application with several modules. My node-application is transpiled with Babel to /dist/app.

This is an example-structure

.
|- main
|   |- config.js
|   |- factories
|   |     |- example.js

This is config.js:

const ex = require("/main/factories/example");

I launch config.js with node dist/app/main/config.js. The resulting error is:

Error: Cannot find module '/main/factories/example";

However when using const ex = require("./factories/example"); it works as it should.

This problem only occurs on Windows (testing Windows 8.1), both OS X and Linux are fine.

What is the problem here?

like image 869
Hedge Avatar asked Oct 22 '25 22:10

Hedge


1 Answers

It's the other way around, the code works as expected on Windows. /main/factories/example means C:/main/factories/example on Windows. It works on OSX/Linux because of some reason (NODE_PATH being set probably). I'd suggest to not rely on a side effect to have a working code and don't use relative path either (entirely dependant on the working directory), you should build your absolute path like this:

const ex = require(__dirname + "/factories/example");
like image 129
Shanoor Avatar answered Oct 24 '25 13:10

Shanoor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!