Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mkdir if not exists using golang

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"); 
like image 318
Alfred Avatar asked Jun 20 '16 22:06

Alfred


People also ask

How do you mkdir only if not exists?

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.

How do I create a folder in Golang?

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() .

What does mkdir do if directory exists?

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.


1 Answers

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.

like image 81
Alfred Avatar answered Oct 01 '22 11:10

Alfred