I am working on creating my first Node.js module, and am having a difficult time trying to decide the best way to handle this. What is the recommended method for receiving paths to files to my module as input by the user? How can I then resolve where that is? Where the user called my module and the location of my running code are in two different places.
Let's take this a step further. Let's say a user has a JSON config file with an array of these paths (in config/settings.json):
{
"paths": [
"../path1",
"path2",
"/path/to/path3",
"~/path4"
]
}
Now obviously these paths are relative to the config file, not any executing code. This feels wrong, as now my method must accept the __dirname
, the path of the config file relative to __dirname
, etc.
var mymodule = require('mine');
mymodule(__dirname, './config/settings.json');
Any files I read from the config must then be based on the location of this config file. This feels weird. Suggestions?
I would avoid complexity and go for absolute paths only. Most users do __dirname + '../relativepath' anyways. ( at least that's what I do ).
From FileUtils source:
var updateFileProperties = function (file, path){
file._path = null;
file._usablePath = null;
file._isAbsolute = false;
if (path === undefined || path === null) return;
path = PATH.normalize (path);
var index = path.indexOf (":") + 1;
var windowsRoot = path.substring (0, index);
path = path.substring (index);
//https://github.com/joyent/node/issues/3066
if (path[0] === "/" && path[1] === "/"){
path = path.replace (/[\/]/g, "\\");
path = path.substring (0, path.length - 1);
}
file._isAbsolute = path[0] === SLASH;
file._path = windowsRoot + path;
file._usablePath = file._isAbsolute ? file._path : (windowsRoot + PATH.join (file._relative, path));
};
var File = function (path){
var main = process.mainModule.filename;
var cwd = main.substring (0, main.lastIndexOf (SLASH));
var relative = PATH.relative (process.cwd (), cwd);
this._relative = relative;
//...omitted
updateFileProperties (this, path);
};
This piece of code resolves the relative path problem.
_usablePath
contains the real path. The "." path will be the directory where the main file is located. No matter how is called, it will point to the expected directory.
You can test the functions printing what the new File (<path>).getPath ()
returns.