I came from Node.js to Go. The Node.js equivalent to __dirname
in Go is:
_, filename, _, ok := runtime.Caller(0)
if !ok {
return errors.New("unable to get the current filename")
}
dirname := filepath.Dir(filename)
Some other mentions in this thread and why they're wrong:
os.Executable()
will give you the filepath of the currently running executable. This is equivalent to process.argv[0]
in Node. This is not true if you want to take the __dirname
of a sub-package.
os.Getwd()
will give you the current working directory. This is the equivalent to process.cwd()
in Node. This will be wrong when you run your program from another directory.
Lastly, I'd recommend against pulling in a third-party package for this use case. Here's a package you can use:
package current
// Filename is the __filename equivalent
func Filename() (string, error) {
_, filename, _, ok := runtime.Caller(1)
if !ok {
return "", errors.New("unable to get the current filename")
}
return filename, nil
}
// Dirname is the __dirname equivalent
func Dirname() (string, error) {
filename, err := Filename()
if err != nil {
return "", err
}
return filepath.Dir(filename), nil
}
Note that I've adjusted runtime.Caller(1)
to 1 because we want to get the directory of the package that called current.Dirname()
, not the directory containing the current
package.