简体   繁体   中英

Gatsby JS, Can't Create Node In Callback

so basically I want to use createNode() within the callback of the file.walk() command, but when I do that, no nodes are created and you can't query the component type in graphiQL.

Uncommenting the other and commenting out the file section allows me to query the component (since it isn't in the callback.)

// Gatsby Node File
const file = require('file');

exports.sourceNodes = async ({ actions, createNodeId, createContentDigest }) => {
  const { createNode } = actions;

  // const components = [{
  //   key: 123,
  //   foo: `ywgavevw`,
  //   bar: `Baz`
  // },
  // {
  //   key: 456,
  //   foo: 'asdfsadf',
  //   bar: 'asdfasdf'
  // }];

  file.walk('./components/', (_, some, thing, files) => {
    console.log(files);

    let component = {
      key: 456,
      foo: 'asdfsadf',
      bar: 'asdfasdf'
    }

    const nodeContent = JSON.stringify(component);

    const nodeMeta = {
      id: createNodeId(`kstat-component-${component.key}`),
      parent: null,
      children: [],
      internal: {
        type: `KstatComponent`,
        mediaType: `text/html`,
        content: nodeContent,
        contentDigest: createContentDigest(component)
      }
    }

    const node = Object.assign({}, component, nodeMeta);
    createNode(node);
  });

  //   components.forEach((component) => {
  //     const nodeContent = JSON.stringify(component);

  //     const nodeMeta = {
  //       id: createNodeId(`kstat-component-${component.key}`),
  //       parent: null,
  //       children: [],
  //       internal: {
  //         type: `KstatComponent`,
  //         mediaType: `text/html`,
  //         content: nodeContent,
  //         contentDigest: createContentDigest(component)
  //       }
  //     }

  //     const node = Object.assign({}, component, nodeMeta);
  //     createNode(node);
  //   });
}

On a higher level, I am trying to achieve creating a number of nodes based on files in the filesystem. Is there a less-crazy way of doing this? Should I consider something else? Thanks!

Have you tried awaiting for the callback?

 await file.walk('./components/', (_, some, thing, files) => {
    console.log(files);

    let component = {
      key: 456,
      foo: 'asdfsadf',
      bar: 'asdfasdf'
    }

    const nodeContent = JSON.stringify(component);

    const nodeMeta = {
      id: createNodeId(`kstat-component-${component.key}`),
      parent: null,
      children: [],
      internal: {
        type: `KstatComponent`,
        mediaType: `text/html`,
        content: nodeContent,
        contentDigest: createContentDigest(component)
      }
    }

    const node = Object.assign({}, component, nodeMeta);
    createNode(node);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM