patterngoCritical
mkdir if not exists using golang
Viewed 0 times
existsusinggolangmkdirnot
Problem
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)
For example in node I would use fs-extra with the function ensureDirSync (if blocking is of no concern of course)
fs.ensureDir("./public");Solution
I've ran across two ways:
-
Check for the directory's existence and create it if it doesn't exist:
However, this is susceptible to a race condition: the path may be created by someone else between the
-
Attempt to create the directory and ignore any issues (ignoring the error is not recommended):
-
Check for the directory's existence and create it if it doesn't exist:
if _, err := os.Stat(path); os.IsNotExist(err) {
err := os.Mkdir(path, mode)
// TODO: handle error
}However, this is susceptible to a race condition: the path may be created by someone else between the
os.Stat call and the os.Mkdir call.-
Attempt to create the directory and ignore any issues (ignoring the error is not recommended):
_ = os.Mkdir(path, mode)Code Snippets
if _, err := os.Stat(path); os.IsNotExist(err) {
err := os.Mkdir(path, mode)
// TODO: handle error
}_ = os.Mkdir(path, mode)Context
Stack Overflow Q#37932551, score: 203
Revisions (0)
No revisions yet.