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");
When you want to create a directory in a path that does not exist then an error message also display to inform the user. If you want to create the directory in any non-exist path or omit the default error message then you have to use '-p' option with 'mkdir' command.
To create a single directory in Go, use the os. Mkdir() function. If you want to create a hierarchy of folders (nested directories), use os. MkdirAll() .
mkdir WILL give you an error if the directory already exists. mkdir -p WILL NOT give you an error if the directory already exists. Also, the directory will remain untouched i.e. the contents are preserved as they were.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With