3

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?

2 Answers 2

9

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)
}
2
  • 2
    Isn't that more process.cwd() rather than __dirname. __dirname is the directory of the source file, whereas a working directory as the docs indicate for os.Getwd is the user's current working directory (what is executing the program)
    – balupton
    May 21, 2019 at 14:53
  • 1
    I agree, in practice .Getwd and __dirname__ are not the same.
    – jcollum
    Jun 23, 2020 at 21:00
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.