Reputation: 3465
I'm studying Go, I don't know if I missed something, but after searching, I wonder: Does dirname in NodeJS have an equivalent in Go? How to get current directory in Go code, or I have to implement one?
Upvotes: 3
Views: 1982
Reputation: 26
I'm studying V and Golang at the same time, and apparently, there's a function called os.Executable()
to have the closest __dirname
equivalent. According to this source, you run the os.Executable()
function to get the directory of where the code is running from, and then do filepath.Dir()
to get only the absolute path without the executable's name.
I just copy-pasted this snippet from the reference, but this is how you get the __dirname
in Go:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
// Getting the path name for the executable
// that started the current process.
pathExecutable, err := os.Executable()
if err != nil {
panic(err)
}
// Getting the directory path/name
dirPathExecutable := filepath.Dir(pathExecutable)
fmt.Println("Directory of the currently running file...")
fmt.Println(dirPathExecutable)
}
And I agree, there's a difference between what the previous answer did. It also works similarly in V, where it would always get the current working directory from where you ran the code. So if you are in your home directory, when running os.Getwd()
, it will print out the home directory rather than where you executed the code.
Upvotes: 1
Reputation: 11551
In Go you can use os.Getwd
which returns a rooted path name corresponding to the current directory.
dir, err := os.Getwd()
if err != nil {
fmt.Errorf("Dir %v does not exists", err)
}
Upvotes: 8