var rootDir = process.cwd(); var config = require(rootDir + '/server/config');
And so forth.
31–40 of 44 posts
var rootDir = process.cwd(); var config = require(rootDir + '/server/config');
And so forth.
Setting an environment variable to include a directory in which you have libraries that you need to use across your application is not a workaround. It's using a feature.
Adding a relative path to a *PATH variable is clever, elegant, useful, and uncommon. It resolves a problem not directly (by changing how 'require' works internally), but indirectly, aka "working around" it.
Applications can be decoupled into interoperable components. Separate modules for configuration, controllers, routing, etc.
Separate concerns into modules.
can't you install a private npm module by npm link? That won't touch the npm servers [1]. Then your other project in the same file system can just require like a first class public npm module. [1] https://www.npmjs.org/doc/cli/npm-link.html
How do you go about setting these links when you freshly checked out a project through source control? There is no "npm link all", is there?
Anyone with this problem is most likely working on a horrible monolith. You have far too much nesting and you're simply hiding the symptoms of a greater problem. Flat > nested. Simple > complex. Law of demeter also applies to reaching and in/out of folders. Break your app into more smaller modules rather than sweeping your mess under the rug.
My usual idiom is to do two things:
1. Part of my boilerplate at the top of every JS file is something like this:
var path = require('path');
var HOMEDIR = path.join(__dirname,'..','..');
where `__dirname` is the built-in variable that names the directory that contains the current file, and `'..','..'` is the requisite number of steps up the directory tree to reach the root of the project.From there is it is simply:
var foo = require(path.join(HOMEDIR,'lib','foo'));
var bar = require(path.join(HOMEDIR,'lib','foo','bar'));
to load an arbitrary file within the project.2. Long before I got to 8 levels deep in the directory tree I'd create a separate npm module to bundle the code together in a less spaghetti fashion.
For what it's worth, I typically use a branch on a private GitHub repository for my "private" modules. I.e., the master branch has the source code, and another (say, `npm-v1.2.3`) has the npm package of it.