Suggest new feature for loading scripts: loadScript and loadFolder
For loading external script into MongoSh current session, currently we have the load()
function, which is enough for the task. But I found myself using my own functions instead. So I would like to describe those as suggestion to improve MongoSh:
loadScript()
This function is basically has the same function with load()
. But has 1 major difference: all relative paths in the script has the same base directory with the script itself, not the current MongoSh working directory.
For example:
- Script "D:\MyProject\src\script.js"
have these references: "test.js"
, "../test2.js"
- Current working dir process.cwd()
: "C:\MongoSh"
- Path resolved using load("D:\MyProject\src\script.js")
: "C:\MongoSh\test.js"
, "C:\test2.js"
- Path resolved using loadScript("D:\MyProject\src\script.js")
: "D:\MyProject\src\test.js"
, "D:\MyProject\test2.js"
My implementation:
const loadScript = function (name) {
const currentDir = path.resolve();
const absPath = path.resolve(name);
try {
process.chdir(path.dirname(absPath));
load(path.basename(absPath));
} catch (e) {
print(e);
}
process.chdir(currentDir);
}
loadFolder()
This function load all scripts in folder and its nested folders (including symbolic links) using loadScript()
behavior.
Why I use this in the first place? Because of .mongoshrc.js
. I have a lot of self implement functions, so I put them all in mongoshrc
folder in the same location with .mongoshrc.js
. And then load them all inside .mongoshrc.js
. But since load()
function do not interpreted relative path based on script location, so I have to change my working directory like this:
{
const currentDir = path.resolve();
process.chdir(`${process.env.HOME ?? process.env.USERPROFILE}/mongoshrc`);
load(`myScripts.js`);
process.chdir(currentDir);
}
It is better if .mongosh.js
loaded with loadScript()
, then the script is just:
loadScript(`mongoshrc/myScripts.js`);
or
loadFolder(`mongoshrc`);
Hope I make myself clear. Thanks for reading.