Switch branches/tags
AnushPatel-patch-1 JanoshRiebesell-patch-1 KyleAMathews-patch-1 Partner-program add-depn add-escalade-sports-case-study add-mobile-performance-post add-plugin-documentation alter-blog-post-date amberleyromo-7730-starter-showcase-sourcing amberleyromo-patch-1 array-doclets berrak-responsive-layout calcsam-patch-1 ccustom-algolia-index change-hacktoberfest-title config-api coreyward-patch-1-1 cypress-timeouts docs-rename-starter docs/gatsby-remark-images-sharp documentation-project-blogpost-new-title drop-alpha-support filter-css fix-broken-link fix-doc fix-docs-reload fix/starter-detail-dependency-grid fix/typescript-reach-router fixes-to-plugin-library gatsby-ssr-silent-fail graphql-filter-sort gvarandas-patch-1 hu0p-patch-1 imagentleman-patch-1 link-container m-allanson-patch-1 marisamorby-swag-store-post master mikeriley131-patch-1 neo/move-prefixPath old-master-3 old-master-4 old-master-6 old-master-7 page-metadata-splitting plugin-blogpost-edit plugin-cli pr/8963 revert-4254-blog-documentation-project revert-5047-update-remark revert-workspaces rfbotto-patch-1 sample-branch-example sebastienfi-wp-orderby-date-asc shannonbux-docs-contributions sharp-images-no-ext sort-chunks starterShowcase2 style-guide-update styled-components-babelrc-config-doc test-builds topics/gatsby-plugin-sharp-tracesvg-fluid topics/inconsistent-accordian-behavior-docs-sidebar topics/using-gatsby-image-design-refresh topics/www-bump-remark-autolink-headers topics/www-sidebar-move-expand-all-down tryzniak-patch-1 update-imagemin-deps updated-style-guide-tutorial-details v1 v2 valse-disable-default-pageview valse-resolve-env worker
Nothing to show
Find file History
pieh chore(release): Publish
 - gatsby-image@2.0.23
 - gatsby-remark-code-repls@2.0.3
 - gatsby-source-contentful@2.0.20
 - gatsby-source-drupal@3.0.14
 - gatsby-source-filesystem@2.0.12
 - gatsby-source-mongodb@2.0.10
 - gatsby-source-wordpress@3.0.20
 - gatsby@2.0.65
Latest commit a3042fd Dec 11, 2018

README.md

gatsby-source-filesystem

Plugin for creating File nodes from the file system. The various "transformer" plugins transform File nodes into various other types of data e.g. gatsby-transformer-json transforms JSON files into JSON data nodes and gatsby-transformer-remark transforms markdown files into MarkdownRemark nodes from which you can query an HTML representation of the markdown.

Install

npm install --save gatsby-source-filesystem

How to use

// In your gatsby-config.js
module.exports = {
  plugins: [
    // You can have multiple instances of this plugin
    // to read source nodes from different locations on your
    // filesystem.
    //
    // The following sets up the Jekyll pattern of having a
    // "pages" directory for Markdown files and a "data" directory
    // for `.json`, `.yaml`, `.csv`.
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `pages`,
        path: `${__dirname}/src/pages/`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `data`,
        path: `${__dirname}/src/data/`,
        ignore: [`**/\.*`], // ignore files starting with a dot
      },
    },
  ],
}

Options

In addition to the name and path parameters you may pass an optional ignore array of file globs to ignore.

They will be added to the following default list:

**/*.un~
**/.DS_Store
**/.gitignore
**/.npmignore
**/.babelrc
**/yarn.lock
**/node_modules
../**/dist/**

How to query

You can query file nodes like the following:

{
  allFile {
    edges {
      node {
        extension
        dir
        modifiedTime
      }
    }
  }
}

To filter by the name you specified in the config, use sourceInstanceName:

{
  allFile(filter: { sourceInstanceName: { eq: "data" } }) {
    edges {
      node {
        extension
        dir
        modifiedTime
      }
    }
  }
}

Helper functions

gatsby-source-filesystem exports two helper functions:

  • createFilePath
  • createRemoteFileNode

createFilePath

When building pages from files, you often want to create a URL from a file's path on the file system. E.g. if you have a markdown file at src/content/2018-01-23-an-exploration-of-the-nature-of-reality/index.md, you might want to turn that into a page on your site at example.com/2018-01-23-an-exploration-of-the-nature-of-reality/. createFilePath is a helper function to make this task easier.

createFilePath({
  // The node you'd like to convert to a path
  // e.g. from a markdown, JSON, YAML file, etc
  node:
  // Method used to get a node
  // The parameter from `onCreateNode` should be passed in here
  getNode:
  // The base path for your files.
  // Defaults to `src/pages`. For the example above, you'd use `src/content`.
  basePath:
  // Whether you want your file paths to contain a trailing `/` slash
  // Defaults to true
  trailingSlash:
})

Example usage

The following is taken from Gatsby Tutorial, Part Seven and is used to create URL slugs for markdown pages.

const { createFilePath } = require(`gatsby-source-filesystem`)

exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  // Ensures we are processing only markdown files
  if (node.internal.type === "MarkdownRemark") {
    // Use `createFilePath` to turn markdown files in our `data/faqs` directory into `/faqs/slug`
    const relativeFilePath = createFilePath({
      node,
      getNode,
      basePath: "data/faqs/",
    })

    // Creates new query'able field with name of 'slug'
    createNodeField({
      node,
      name: "slug",
      value: `/faqs${relativeFilePath}`,
    })
  }
}

createRemoteFileNode

When building source plugins for remote data sources such as headless CMSs, their data will often link to files stored remotely that are often convenient to download so you can work with them locally.

The createRemoteFileNode helper makes it easy to download remote files and add them to your site's GraphQL schema.

createRemoteFileNode({
  // The source url of the remote file
  url: `https://example.com/a-file.jpg`,

  // The redux store which is passed to all Node APIs.
  store,

  // Gatsby's cache which the helper uses to check if the file has been downloaded already. It's passed to all Node APIs.
  cache,

  // The action used to create nodes
  createNode,

  // A helper function for creating node Ids
  createNodeId,

  // OPTIONAL
  // Adds htaccess authentication to the download request if passed in.
  auth: { htaccess_user: `USER`, htaccess_pass: `PASSWORD` },

  // OPTIONAL
  // Sets the file extension
  ext: ".jpg",
})

Example usage

The following example is pulled from gatsby-source-wordpress. Downloaded files are created as File nodes and then linked to the WordPress Media node, so it can be queried both as a regular File node and from the localFile field in the Media node.

const { createRemoteFileNode } = require(`gatsby-source-filesystem`)

exports.downloadMediaFiles = ({
  nodes,
  store,
  cache,
  createNode,
  createNodeId,
  _auth,
}) => {
  nodes.map(async node => {
    let fileNode
    // Ensures we are only processing Media Files
    // `wordpress__wp_media` is the media file type name for Wordpress
    if (node.__type === `wordpress__wp_media`) {
      try {
        fileNode = await createRemoteFileNode({
          url: node.source_url,
          store,
          cache,
          createNode,
          createNodeId,
          auth: _auth,
        })
      } catch (e) {
        // Ignore
      }
    }

    // Adds a field `localFile` to the node
    // ___NODE appendix tells Gatsby that this field will link to another node
    if (fileNode) {
      node.localFile___NODE = fileNode.id
    }
  })
}

The file node can then be queried using GraphQL. See an example of this in the gatsby-source-wordpress README where downloaded images are queried using gatsby-transformer-sharp to use in the component gatsby-image.

Retrieving the remote file extension

The helper tries first to retrieve the file extension by parsing the url and the path provided (e.g. if the url is https://example.com/image.jpg, the extension will be inferred as .jpg). If the url does not contain an extension, we use the file-type package to infer the file type. Finally, the extension can be explicitly passed, like so:

createRemoteFileNode({
  // The source url of the remote file
  url: `https://example.com/a-file-without-an-extension`,
  store,
  cache,
  createNode,
  createNodeId,
  // if necessary!
  ext: ".jpg",
})