When you write a library that will be used by another code base you cannot be sure where exactly NPM or yarn (or whatever package manager you choose) will install your library. It may be directly in node_modules
but it may be nested depending upon the use case. However, as indicated by the stackoverflow answer here the process.main.filename
variable will tell us exactly where the main process that is calling us lives. We can use this value to determine where the config file you want to read exists.
Here is some example code:
The config-lib
library reads a configuration.
index.js
file:
const fs = require("fs");
const path = require("path");
const promisify = require("util").promisify;
const readFilep = promisify(fs.readFile);
module.exports = async function loadConfig(filename = "config.json") {
const configPath = path.resolve(
path.dirname(require.main.filename),
filename
);
console.log("(load-config lib) Config Path: " + configPath);
try {
const data = await readFilep(configPath, "utf8");
return JSON.parse(data);
} catch (err) {
console.log(err);
}
};
This library has a simple package.json
{
"name": "config-lib",
"version": "1.0.0",
"description": "I read a config",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Some Cool Guy <somecoolguy@example.com>",
"license": "MIT"
}
Now the project itself requires this library. Here is the projects package.json
{
"name": "project",
"version": "1.0.0",
"description": "I am the project",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Some Other Cool Guy <someoneelse@example.com>",
"license": "MIT",
"dependencies": {
"config-lib": "file:../lib"
}
}
(The config-lib
library in this example was loaded from a local folder.)
The config-lib
library requires me, in my project, to create a configuration file called config.json
(BTW... name it something more specific to your library as to not collide with a local project configuration if they have one).
Here is an example config.json
:
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Finally, in my project I can use the config-lib
library to read my configuration file:
const configLib = require("config-lib");
(async () => {
console.log("Reading config");
const data = await configLib();
console.log("Here is my config: " + JSON.stringify(data));
console.log("key1 value: " + data.key1);
})();