[SOLVED] Os.fileinfo.modtime

I use a json data file to generate a page.
I need access to os.FileInfo.ModTime() to show the modification time of the data file.

{{ $file := "/data/links.json" }}
{{ $dstat := (os.Stat $file).ModTime ?? }}

Nice to see it in the next release :wink:

How about:

I havenโ€™t tested this myself, but reading through the hugo docs for os.Stat, it mentions

Function os.Stat returns os.FileInfo . For further information of os.FileInfo , see golang page.

Then that golang page says the interface for os.FileInfo includes ModTime

type FileInfo interface {
        Name() string       // base name of the file
        Size() int64        // length in bytes for regular files; system-dependent for others
        Mode() FileMode     // file mode bits
        ModTime() time.Time // modification time
        IsDir() bool        // abbreviation for Mode().IsDir()
        Sys() interface{}   // underlying data source (can return nil)

Yep, but I donโ€™t use Git!

I have seen this,

.Name and .Size works fine, how to get the ModTime?
I looked in the sources, but there is no function for it.

Try it like this:

{{ $file := "data/links.json" }}
{{ $stat :=  os.Stat $file }}
{{ $stat.Name }}
{{ $stat.ModTime }}

I was curious about os.Stat and what it can do, so made a little sample project.

I put a dummy JSON file at data/links.json:

    "link": "https://gohugo.io/functions/os.stat/"

And this HTML file at layouts/index.html:

<!doctype html>
<html lang="en">
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <title>os.Stat Testing</title>
    <h1>os.Stat Testing</h1>

    {{ $file := "data/links.json" }}
    {{ $stat :=  os.Stat $file }}
    <p>File Name: <code>{{ $stat.Name }}</code></p>
    <p>File Size: <code>{{ $stat.Size }}</code> bits</p>
    <p>File Mode: <code>{{ $stat.Mode }}</code></p>
    <p>File ModTime: <code>{{ $stat.ModTime }}</code></p>
    <p>File IsDir: <code>{{ $stat.IsDir }}</code></p>
    <p>File Sys: <code>{{ $stat.Sys }}</code></p>


Which gives me this output:

Sample repo: https://github.com/zwbetz-gh/hugo-os-stat-test



my solution looks now:

datafile = "/data/links.json"

{{ $file := .Params.datafile}}
{{ $data := getJSON $file }}
{{ range $data.items }}
etc ..

{{ with .Params.datafile }}
{{ $stat := os.Stat . }}
changed: {{$stat.ModTime.Format $.Site.Params.dateFormatLong}}
{{ end }}

1 Like