I am learning golang(beginner) and I have been searching on both google and stackoverflow but I could not find an answer so excuse me if already asked, but how can I mkdir if not exists in golang.
For example in node I would use fs-extra with the function ensureDirSync (if blocking is of no concern of course)
fs.ensureDir("./public");
I've ran across two ways:
Check for the directory's existence and create it if it doesn't exist:
if _, err := os.Stat(path); os.IsNotExist(err) {
os.Mkdir(path, mode)
}
Attempt to create the directory and ignore any issues:
_ = os.Mkdir(path, mode)
Okay I figured it out thanks to this question/answer
import(
"os"
"path/filepath"
)
newpath := filepath.Join(".", "public")
os.MkdirAll(newpath, os.ModePerm)
MkdirAll creates a directory named path, along with any necessary parents, and returns
nil
, or else returns anerror
.
You can use os.Stat
to check if a given path exists.
If it doesn't, you can use os.Mkdir
to create it.
This is one alternative for achieving the same but it avoids race condition caused by having two distinct "check ..and.. create" operations.
package main
import (
"fmt"
"os"
)
func main() {
if err := ensureDir("/test-dir"); err != nil {
fmt.Println("Directory creation failed with error: " + err.Error())
os.Exit(1)
}
// Proceed forward
}
func ensureDir(dirName string) error {
err := os.Mkdir(dirName, os.ModeDir)
if err == nil || os.IsExist(err) {
return nil
} else {
return err
}
}