6

I'm writing JavaScript code for MongoDB shell in client. How can I get the path of the script file which is executing? Please note it's not the value of pwd(). For example, I'm executing /my_scripts/utils.js from /my_path:

> mongodb --nodb /my_scripts/utils.js

so pwd() returns /my_path, but how can I get the full path (or relative path to the value of pwd()) of the current executing file, which is /my_scripts/utils.js?

Jeffrey Zhao
  • 4,923
  • 4
  • 30
  • 52

3 Answers3

2

in case you are still wondering, you can call pwd() from inside your script to get the path where your script

More information about pwd() can be found in the MongoDb manual: https://docs.mongodb.com/manual/reference/method/pwd

Nick
  • 37
  • 4
  • For me, pwd() does not return the path where the script is running e.g. /home/mysername/scripts. It just returns the home directory e.g. /home/mysername/. And load('./myfile.js') seems to be relative to the home directory, not the actual location of the script. So I don't think this answers the question. – Little Brain Nov 11 '20 at 15:28
  • The link is broken :( – benshabatnoam Dec 13 '22 at 09:38
  • I think that's the link you need - https://www.mongodb.com/docs/v5.2/reference/method/pwd/ Or maybe event better (because it's deprecated) try this one - https://www.mongodb.com/docs/v5.2/reference/method/js-native/#std-label-native-in-mongosh and search for pwd() in the doc – benshabatnoam Dec 13 '22 at 09:44
0

you can try bash shell/a.sh,write pwd command into file a.sh

Raghava
  • 22
  • 2
0

you can run your utils.js from a shell script.

usage:

./run.sh path_to_utils.js

run.sh

#!/bin/sh

// $1 is path_to_utils.js
echo $1

mongo < $1

e.g:

./run.sh ~/Downloads/t.js
/Users/sunus/Downloads/t.js
MongoDB shell version: 2.6.2
connecting to: test
Hello
bye
sunus
  • 838
  • 9
  • 11