1

Here's my architecture:

.
├── app.js
├── package-lock.json
├── package.json
└── src
    ├── controller
    │   └── index.controller.js
    └── route
        └── index.route.js

.env

NODE_PATH=./src

index.route.js

const express = require('express');

const Router = express.Router();

const { root } = require('controller/index.controller');      <--- Failed

Router.get('/', root);

module.exports = {
  Router
};

index.controller.js

const express = require('express');

const root = (req, res) => {
  res.status(200).send('root');
};

console.log('controller');

module.exports = {
  root
};

I would like to use an .env file with a NODE_PATH to easily import module in my .js file and avoid those kind of pattern ../../../folder/folder/module.js

However when I do node app.js. Node doesn't seem to care about the .env An error occur in index.route.js

Error: Cannot find module 'controller/index.controller'

Does someone can explain me why node doesn't care about the NODE_PATH I set ?

Thanks

S7_0
  • 1,165
  • 3
  • 19
  • 32
  • 1
    I would suggest to refer below link https://stackoverflow.com/questions/20185627/node-js-node-path-environment-variable. It must work for you. Instead of configuring in .env file we can give it in scripts of package.json – Amaranadh Meda Aug 13 '19 at 05:49
  • 1
    I just try, it work. :) But I'm curious to know if it's possible only by using the .env file ? – S7_0 Aug 13 '19 at 05:59
  • im on the same boat as you, did you ever find a solution? ive managed to do this with react in the past, but for some reason on a clean node install backend it aint working > – xunux Feb 07 '20 at 17:55

1 Answers1

0

To access .env file, assign process.env.NODE_PATH to a variable like below

let temp = process.env.NODE_PATH

now in your require statement

require(temp + '/controller/index.controller'); 

Note- I haven't tested it, but it should work

Ram
  • 356
  • 2
  • 14
  • It doesn't work. In your require statement "temp" it's part of the string so node doesn't know that it should represent process.env.NODE_PATH – S7_0 Aug 13 '19 at 05:51
  • But you got the idea, i hope – Ram Aug 13 '19 at 05:52
  • Oh yeah I got the idea haha but is there an other way to do without use process.env.NODE_PATH in the code ? – S7_0 Aug 13 '19 at 06:00