Kevin S
Kevin S

Reputation: 531

How to access text contents of file returned by a "file" or "allFiles" GraphQL query in Gatsby?

I'm trying to access the contents of a text file returned by a "file" GraphQL query in Gatsby (via the gatsby-source-filesystem plugin). The query is definitely returning a File node. The problem is that I'm expecting the internal>contents field to contain the contents of the file, but it does not; it's always null. Here an example query and result, as obtained using Gatsby's GraphiQL browser. The question is (1) what am I doing wrong, and (2) what should I do to achieve my intent of accessing the file contents?

Query

query MyQuery {
  file(ext: {eq: ".lean"}, name: {eq: "test"}) {
    name
    relativePath
    size
    internal {
      content
      mediaType
    }
  }
}

Result

{
  "data": {
    "file": {
      "name": "test",
      "relativePath": "test.lean",
      "size": 10,
      "internal": {
        "content": null,
        "mediaType": "application/octet-stream"
      }
    }
  }
}

As you can see from the result, the file isn't empty (the file has one short line of Lean Prover code inside), but the value of the internal>content field is nevertheless null. I'm obviously doing something wrong, but after an hour of trying to figure out what, I figure someone else might also benefit from a quick answer. Thanks for shedding light on my issue.

Upvotes: 5

Views: 1198

Answers (1)

Kevin S
Kevin S

Reputation: 531

Ok, so gatsby-source-filesystem actually exports a helper method, loadNodeContents (which of course just reads from the file). The only problem is that this is not documented on the public docs site for this plugin. Here's the file where the relevant code appears. https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-filesystem/src/index.js

Upvotes: 5

Related Questions