Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I require something in root project directory from inside node package library?

I wanna create a node package modules, but I have difficulty to require a file from root project directory to use inside my node package module I created.

If I have directory structure like this

- node_modules
  - library_name
    - lib
      - index.js
    - bin
      - run.sh
-  config.js

If the run.sh called, it will run index.js. Inside index.js, how do I resolve to root directory which later I can require config.js inside index.js?

like image 995
Jefry Dewangga Avatar asked Mar 11 '26 23:03

Jefry Dewangga


2 Answers

Package binary can accept configuration path explicitly as an argument.

If package binary doesn't run as NPM script, it shouldn't rely on parent project structure.

If package binary runs via NPM script:

"scripts": {
  "foo": "library_name"
}

This will set current working directory to project root, so it could be required as:

const config = require(path.join(process.cwd(), 'config'));

Both approaches can be combined; this is often used to provide configuration files with default locations to third-party CLI (Mocha, etc).

like image 195
Estus Flask Avatar answered Mar 14 '26 13:03

Estus Flask


If you're in index.js and config.js is in the directory above node_modules in your diagram, then you can build a path to config.js like this:

const path = require('path');
let configFilename = path.join(__dirname, "../../../", "config.js");

__dirname is the directory that index.js is in.

The first ../ takes you up to the library_name directory.

The second ../ takes you up to the node_modules directory.

The third ../ takes you up to the parent of node_modules (what you call project root) where config.js appears to be.


If you really want your module to be independent of how it is installed or how NPM might change in the future, then you need to somehow pass in the location of the config file in any number of ways:

  1. By making sure the current working directory is set to the project root so you can use process.cwd() to get access to the config file.
  2. By setting an environment variable to the root directory when starting your project.
  3. By passing the root directory in to a module constructor function.
  4. By loading and passing the config object itself in to a module constructor function.
like image 23
jfriend00 Avatar answered Mar 14 '26 12:03

jfriend00



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!