Embed Directive in JavaScript

Here’s the translation of the Go code to JavaScript, formatted in Markdown suitable for Hugo:

Our first example demonstrates how to include external files and folders in a JavaScript project. While JavaScript doesn’t have a direct equivalent to Go’s embed directive, we can achieve similar functionality using Node.js and the fs module.

// Import the fs module for file system operations
const fs = require('fs');
const path = require('path');

// Read the contents of a single file
const fileString = fs.readFileSync(path.join(__dirname, 'folder', 'single_file.txt'), 'utf8');
const fileByte = fs.readFileSync(path.join(__dirname, 'folder', 'single_file.txt'));

// Read multiple files from a folder
const folder = {
    readFile: (filename) => fs.readFileSync(path.join(__dirname, filename))
};

function main() {
    // Print out the contents of 'single_file.txt'
    console.log(fileString);
    console.log(fileByte.toString());

    // Retrieve some files from the folder
    const content1 = folder.readFile('folder/file1.hash');
    console.log(content1.toString());

    const content2 = folder.readFile('folder/file2.hash');
    console.log(content2.toString());
}

main();

To set up the folder structure and files for this example, you can use the following commands in your terminal:

$ mkdir -p folder
$ echo "hello javascript" > folder/single_file.txt
$ echo "123" > folder/file1.hash
$ echo "456" > folder/file2.hash

Then, you can run the JavaScript file using Node.js:

$ node embed-example.js
hello javascript
hello javascript
123
456

In this JavaScript version, we use the fs module to read files synchronously. The readFileSync function is used to read the contents of individual files, both as strings and as raw buffers.

To emulate the behavior of embedding multiple files or folders, we create a simple object called folder with a readFile method. This method reads files from the specified folder.

Note that unlike Go’s embed directive, which includes the files in the binary at build time, this JavaScript approach reads the files at runtime. For a more robust solution in a production environment, you might want to consider using a bundler like Webpack or Rollup to include external files in your JavaScript bundle.