About how to load modules with absolute paths in Node.js. In Node.js, you can load modules and external files with relative paths, but you need a little ingenuity to load them with absolute paths.
Until recently, I was requiring external modules in a format like the following. It seemed to be working well. However.
var noderc = require( path.relative( __dirname , process.env.NODE_RC_FILE ) );
Actually, the above code is incomplete and causes an error when the reference path is in the same level directory.
module.js:550
throw err;
^
Error: Cannot find module 'noderc.js'
at Function.Module._resolveFilename (module.js:548:15)
at Function.Module._load (module.js:475:25)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/mnt/c/pg/node/tmp.js:10:14)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
Why? When there’s a reference path in the same level, it returns a value as a path like noderc.js rather than a path like ./noderc.js.
To put it clearly, it’s like this:
var noderc = require( "noderc.js" ); # => ERROR
var noderc = require( "../node/noderc.js" ); # => OK
var noderc = require( "./noderc.js" ); # => OK
So I wrote the following. When the path is something like “noderc.js”, it converts it to ”./noderc.js”.
global.require_absolute = function( filepath ){
if ( ! /^\./.test( path.relative( __dirname , filepath ) ) ){
global.noderc = require( `./${ path.relative( __dirname , filepath ) }` );
} else {
global.noderc = require( path.relative( __dirname , filepath ) );
}
}
And usage example:
require_absolute( "/mnt/c/pg/node/noderc.js" ) ;
require_absolute( process.env.NODE_RC_FILE ) ;
There seems to be deep discussion about Node.js require. This topic alone has 2000 stars.
Better local require() paths for Node.js
Update
Sorry, I was mistaken. The following is more versatile:
global.to_relative = function( filepath ){
if ( ! /^\./.test( path.relative( __dirname , filepath ) ) ){
return `./${ path.relative( __dirname , filepath ) }` ;
} else {
return path.relative( __dirname , filepath ) ;
}
}
var noderc = require( to_relative( process.env.NODE_RC_FILE ) ) ;