Quantum
Quest

Algorithms, Math, and Physics

Raw contents include plugin

Today I created include_raw_contents plugin for Hexo blogs. This plugin allows to include the raw content of any file directly into a blog post as raw html, making it useful for sharing code snippets, configuration files, or any html content without the need of copying and pasting it into Markdown file.

Example usage

Below, we will include the contents of a sample html file named 2024/02/raw-contents-plugin.html that resides in source/_raw directory:

*** Start of Imported HTML ***

Interesting Facts About Space

Space is incredibly vast and fascinating. Here are a few intriguing facts:

  • The closest galaxy to us is the Andromeda Galaxy, and it's estimated to collide with the Milky Way in about 4 billion years.
  • A day on Venus is longer than a year on Venus. It takes 243 Earth days to complete one rotation on its axis, but only 225 Earth days to complete an orbit around the Sun.
  • Neutron stars are so dense that a sugar-cube-sized amount of material from one would weigh about as much as all of humanity.

*** End of Imported HTML ***

The content of the file is seamlessly integrated into this post, maintaining its original formatting and structure. This feature is particularly useful for technical posts, tutorials, and documentation where direct references to external files might be needed or an html version is already available.

Plugin code



const fs = require('hexo-fs');
const path = require('path');

hexo.extend.tag.register('include_raw_contents', async function(args) {
  // Join the arguments to allow spaces in filenames
  const relativeFilePath = args.join(' ');

  // Construct the absolute path to the file within the _raw directory
  const actualFilePath = path.join(hexo.base_dir, 'source', '_raw', relativeFilePath);

  // Check if the file exists and read its content
  if (await fs.exists(actualFilePath)) {
    const content = await fs.readFile(actualFilePath);
    return content;
  } else {
    hexo.log.error(`File not found: ${actualFilePath}`);
    return '';
  }
}, { async: true});

Benefits

  • Ease of Use: Placing html files in the source/_raw directory and use the include_raw_contents tag in posts.
  • Maintainability: Update html files without having to manually update each blog post in markdown.
  • Versatility: Include any html-based content, from code snippets to configuration files.