如何根据目录文件列表自动创建JavaScript变量?(无法使用PHP)
Hey there! Since client-side JavaScript can’t directly read local directories and you can’t use PHP, here are several practical workarounds to automatically generate that sounds object you need:
1. Build-Time Script with Node.js
The most reliable approach is to generate the sounds variable before deploying your code using a simple Node.js script. This way, you don’t have to manually update the object every time you add a new sound file.
Here’s a quick example script you can run:
const fs = require('fs'); const path = require('path'); // Define your sound directory path const soundDir = path.join(__dirname, 'sound'); const sounds = {}; // Loop through all files in the sound directory fs.readdirSync(soundDir).forEach(file => { // Only process MP3 files if (path.extname(file).toLowerCase() === '.mp3') { // Use the filename (without extension) as the key const soundName = path.basename(file, '.mp3'); sounds[soundName] = { url: `sound/${file}` }; } }); // Write the generated object to a JS file fs.writeFileSync( path.join(__dirname, 'generated-sounds.js'), `var sounds = ${JSON.stringify(sounds, null, 2)};` );
Just run this script (node generate-sounds.js) whenever you add new audio files, then include generated-sounds.js in your HTML. It’ll automatically keep your sounds object up to date.
2. Static JSON Manifest File
If you don’t want to use Node.js, you can maintain a simple JSON file that lists all your sound files, then fetch it in your JavaScript to build the sounds object. This is less automated than the build script, but still easier than updating the variable manually every time.
First, create a sound-manifest.json file in your project:
{ "hello": "sound/hello.mp3", "gasp": "sound/gasp.mp3", "scream": "sound/scream.mp3" }
Then fetch it in your JS:
let sounds = {}; // Fetch the manifest and build the sounds object fetch('sound-manifest.json') .then(response => response.json()) .then(manifest => { sounds = Object.fromEntries( Object.entries(manifest).map(([name, url]) => [name, { url }]) ); // Use the sounds object here or trigger your audio logic });
Just remember to update the JSON file whenever you add a new sound.
3. Static Site Generator (SSG) Integration
If you’re using a static site generator like Eleventy, Gatsby, or Hugo, you can leverage their build-time capabilities to automatically generate the sounds variable directly in your HTML or JS files.
For example, with Eleventy, you can create a collection for your sound files (configure this in .eleventy.js), then use a template to output the object:
<script> var sounds = { {% for sound in collections.sounds %} "{{ sound.basenameWithoutExtension }}": { url: "{{ sound.url }}" }{% if not loop.last %},{% endif %} {% endfor %} }; </script>
When you build your site, Eleventy will loop through all your sound files and inject the correct data into the script tag—no manual updates needed.
4. Server Directory Index Parsing (If Server Allows)
If your web server (Apache, Nginx, etc.) is configured to show directory listings (autoindex), you can fetch the sound directory’s index page, parse the HTML, and extract the MP3 file names to build your sounds object.
Note: This depends on your server’s configuration, and parsing HTML can be fragile if the server’s index page layout changes. Here’s a rough example:
fetch('sound/') .then(response => response.text()) .then(html => { const parser = new DOMParser(); const doc = parser.parseFromString(html, 'text/html'); // Select all links pointing to MP3 files const mp3Links = doc.querySelectorAll('a[href$=".mp3"]'); const sounds = {}; mp3Links.forEach(link => { const fileName = link.getAttribute('href'); const soundName = fileName.replace(/^sound\/|\.mp3$/g, ''); sounds[soundName] = { url: fileName }; }); // Use the sounds object here });
Make sure your server has directory indexing enabled for this to work.
内容的提问来源于stack exchange,提问作者Cain Nuke

