golang/go · error
could not create module cache: %q is not a directory
Error message
could not create module cache: %q is not a directory
What it means
Thrown inside checkCacheDir when os.Stat succeeds (the path exists) but fi.IsDir() is false — the GOMODCACHE path resolves to a regular file, symlink-to-file, or device, not a directory. The module cache must be a directory.
Source
Thrown at src/cmd/go/internal/modfetch/cache.go:843
}
// os.Stat is slow on Windows, so we only call it once to prevent unnecessary
// I/O every time this function is called.
statCacheOnce.Do(func() {
fi, err := os.Stat(cfg.GOMODCACHE)
if err != nil {
if !os.IsNotExist(err) {
statCacheErr = fmt.Errorf("could not create module cache: %w", err)
return
}
if err := os.MkdirAll(cfg.GOMODCACHE, 0o777); err != nil {
statCacheErr = fmt.Errorf("could not create module cache: %w", err)
return
}
return
}
if !fi.IsDir() {
statCacheErr = fmt.Errorf("could not create module cache: %q is not a directory", cfg.GOMODCACHE)
return
}
})
return statCacheErr
}
View on GitHub (pinned to b6b368adc5)
Solutions
- Identify what the path currently is: 'file $(go env GOMODCACHE)'.
- Remove or move the offending file: 'rm $(go env GOMODCACHE)'.
- Retry the go command — it will auto-create the directory.
- If the file was created by mistake, investigate which tool/script wrote it.
Example fix
# before: GOMODCACHE is a file $ file $(go env GOMODCACHE) /home/user/go/pkg/mod: ASCII text # after rm $(go env GOMODCACHE) go build ./...
Defensive patterns
Strategy: validation
Validate before calling
func validateGOMODCACHEIsDir(gomodcache string) error {
fi, err := os.Stat(gomodcache)
if os.IsNotExist(err) {
return nil // will be created
}
if err != nil {
return err
}
if !fi.IsDir() {
return fmt.Errorf("GOMODCACHE %q exists but is not a directory", gomodcache)
}
return nil
} Type guard
null
Try / catch
null
Prevention
- Never redirect file output to the GOMODCACHE path.
- In setup scripts, os.Stat the path and assert IsDir before running go.
- Use a dedicated, predictable cache path that no other tool writes to.
- Document the cache location for your team to prevent accidental file creation.
When it happens
Trigger: Running any module-aware go command when GOMODCACHE points at an existing file. Common after someone accidentally writes output to the cache path, or a misconfigured tool creates a file where a directory is expected.
Common situations: A stray 'go env -w GOMODCACHE=~/go' when ~/go was previously a file; a CI script that redirects output to the cache path; a symlink pointing at a file.
Related errors
- GOMODCACHE entry is relative; must be absolute path: %q
- could not create module cache: %w
- file is empty
- GOPATH entry is relative; must be absolute path: %q
- %s entry is relative; must be absolute path: %q
AI-assisted analysis of golang/go@b6b368adc5 (2026-08-12).
Data as JSON: /api/errors/8424335022e14c4d.
Report an issue: GitHub.