In nodejs I use __dirname . What is the equivalent of this in Golang?
I have googled and found out this article http://andrewbrookins.com/tech/golang-get-directory-of-the-current-file/ . Where he uses below code
_, filename, _, _ := runtime.Caller(1)
f, err := os.Open(path.Join(path.Dir(filename), "data.csv"))
But is it the right way or idiomatic way to do in Golang?
As stated in the comment, this returns the directory which is currently active.
Use package osext
It's providing function
ExecutableFolder()
that returns an absolute path to folder where the currently running program executable reside (useful for cron jobs). It's cross platform.Online documentation
If you use package osext by kardianos and you need to test locally, like Derek Dowling commented:
The solution to this is to make a gorun.exe utility instead of using go run. The gorun.exe utility would compile the project using "go build", then run it right after, in the normal directory of your project.
I had this issue with other compilers and found myself making these utilities since they are not shipped with the compiler... it is especially arcane with tools like C where you have to compile and link and then run it (too much work).
If anyone likes my idea of gorun.exe (or elf) I will likely upload it to github soon..
Sorry, this answer is meant as a comment, but I cannot comment due to me not having a reputation big enough yet.
Alternatively, "go run" could be modified (if it does not have this feature already) to have a parameter such as "go run -notemp" to not run the program in a temporary directory (or something similar). But I would prefer just typing out gorun or "gor" as it is shorter than a convoluted parameter. Gorun.exe or gor.exe would need to be installed in the same directory as your go compiler
Implementing gorun.exe (or gor.exe) would be trivial, as I have done it with other compilers in only a few lines of code... (famous last words ;-)
os.Executable
: https://tip.golang.org/pkg/os/#Executablefilepath.EvalSymlinks
: https://golang.org/pkg/path/filepath/#EvalSymlinksFull Demo:
if you use this way :
you will get the /tmp path when you are running program using some IDE like GoLang because the executable will save and run from /tmp
i think the best way for getting the currentWorking Directory or '.' is :
the os.Getwd() function will return the current working directory.
This should do it: