Skip to content

Writing files to disk

Eduardo Bouças edited this page Feb 5, 2020 · 1 revision

Sourcebit provides an easy way for plugins to write files to disk without having to implement the write mechanism themselves. Instead, plugins can simply append objects to the files data bucket as part of the transform method. These objects will get picked up and written to disk after all plugins have finished running.

The objects should have three properties: content (Object), format (String) and path (String). The following table outlines how to use these properties for each of the file formats supported.

format content path Description
frontmatter-md Object containing a frontmatter and body properties, which will be written to the file's frontmatter and content body, respectively The absolute path to the file. Must end with .md. Writes a Markdown file with a YAML frontmatter.
yml Object to be written as YAML The absolute path to the file. Must end with .yaml or .yml Writes a YAML file.
json Object to be written as JSON The absolute path to the file. Must end with .json. Writes a JSON file

💡 If you wish to create multiple files for an entry, set the return value to an array of objects, each containing a content, format and path properties.

✏️ Example: writing JSON file
module.exports.transform = ({ data }) => {
  const newFile = {
    content: {
      name: 'John Doe'
    },
    format: 'json',
    path: '/Users/johndoe/test.json'
  }

  return {
    ...data,
    files: data.files.concat(newFile)
  };
};
✏️ Example: writing Markdown file with frontmatter
module.exports.transform = ({ data }) => {
  const newFile = {
    content: {
      body: 'My name is John',
      frontmatter: {
        name: 'John Doe'
      }
    },
    format: 'frontmatter-md',
    path: '/Users/johndoe/test.md'
  }

  return {
    ...data,
    files: data.files.concat(newFile)
  };
};
✏️ Example: writing YAML file
module.exports.transform = ({ data }) => {
  const newFile = {
    content: {
      name: 'John Doe'
    },
    format: 'yml',
    path: '/Users/johndoe/test.yml'
  }

  return {
    ...data,
    files: data.files.concat(newFile)
  };
};
Clone this wiki locally