Reputation: 61771
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");
Upvotes: 164
Views: 157501
Reputation: 394
you can use this for making new directory in golang:
package main
import (
"fmt"
"os"
)
func main() {
// Specify the directory path you want to create
dirPath := "my_directory"
// Create the directory with the specified path
err := os.Mkdir(dirPath, 0755) // 0755 sets permissions for the directory
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Directory created:", dirPath)
}
I hope it will be helpful for you
Upvotes: 1
Reputation: 358
To create a directory if it does not exist, you can follow these steps:
Import the "os" package at the beginning of your Go program. Use the "os.Mkdir()" function to create the directory.
package main
import (
"fmt"
"os"
)
func main() {
// Specify the path of the directory you want to create
directoryPath := "./my_directory"
// Check if the directory already exists
if _, err := os.Stat(directoryPath); os.IsNotExist(err) {
// The directory does not exist, so create it using os.MkdirAll()
err := os.MkdirAll(directoryPath, 0755) // 0755 sets the permissions for the directory
if err != nil {
fmt.Println("Error creating directory:", err)
return
}
fmt.Println("Directory created successfully.")
} else {
fmt.Println("Directory already exists.")
}
}
Upvotes: 1
Reputation: 235
So what I have found to work for me is:
import (
"os"
"path/filepath"
"strconv"
)
//Get the cur file dir
path, err := filepath.Abs("./") // current opened dir (NOT runner dir)
// If you want runner/executable/binary file dir use `_, callerFile, _, _ := runtime.Caller(0)
// path := filepath.Dir(callerFile)`
if err != nil {
log.Println("error msg", err)
}
//Create output path
outPath := filepath.Join(path, "output")
//Create dir output using above code
if _, err = os.Stat(outPath); os.IsNotExist(err) {
var dirMod uint64
if dirMod, err = strconv.ParseUint("0775", 8, 32); err == nil {
err = os.Mkdir(outPath, os.FileMode(dirMod))
}
}
if err != nil && !os.IsExist(err) {
log.Println("error msg", err)
}
I like the portability of this.
Upvotes: 4
Reputation: 3538
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 {
return nil
}
if os.IsExist(err) {
// check that the existing path is a directory
info, err := os.Stat(dirName)
if err != nil {
return err
}
if !info.IsDir() {
return errors.New("path exists but is not a directory")
}
return nil
}
return err
}
Upvotes: 9
Reputation: 61771
Okay I figured it out thanks to this question/answer
import(
"os"
"path/filepath"
)
newpath := filepath.Join(".", "public")
err := os.MkdirAll(newpath, os.ModePerm)
// TODO: handle error
Relevant Go doc for MkdirAll:
MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error.
...
If path is already a directory, MkdirAll does nothing and returns nil.
Upvotes: 252
Reputation: 22040
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) {
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)
Upvotes: 200
Reputation: 69
Or you could attempt creating the file and check that the error returned isn't a "file exists" error
if err := os.Mkdir(path, mode); err != nil && !os.IsExist(err) {
log.Fatal(err)
}
Upvotes: 2