前端读取同目录文件并在index.html的div中展示问题求助
fs) Hey Erik! I totally get where you're coming from—trying to use Node.js's fs module in the browser always trips people up, since that API only works on the server side. Let's walk through a clean, browser-native solution to get your dynamic content working.
The core issue here:
require("fs")is a Node.js-specific feature, and browsers don't have access to it. Browsers run in a sandboxed environment and can't directly read files from the filesystem like a server can. Instead, we need to use browser APIs to fetch the file over HTTP (even if it's in the same directory).
The Fix: Use the Fetch API
The fetch() API is the standard way to request resources (like your local file) in the browser. Here's how to update your videos() function to use it:
function videos() { // Replace "insertfilename" with your actual file path (e.g., "./content.txt") fetch("insertfilename") .then(response => { // Check if the request was successful if (!response.ok) { throw new Error(`Could not load file: ${response.statusText}`); } // Read the file content as text return response.text(); }) .then(body => { console.log(body); // Insert the content into your div document.getElementById("body").innerHTML = body; }) .catch(error => { // Handle errors (e.g., file not found) console.error("Error loading file:", error); document.getElementById("body").innerHTML = "Oops, couldn't load the content!"; }); }
Key Notes to Make This Work Smoothly
- File Paths: Make sure the path you pass to
fetch()is relative to yourindex.htmlfile. If the file is in the same folder, just use"./filename.ext"(the./is optional but makes the relationship clear). - Local Testing: If you're opening
index.htmldirectly via thefile://protocol (double-clicking it), you might run into CORS errors. To fix this, serve your files with a local web server—tools like Live Server (for VS Code) orhttp-server(npm package) work great. - File Types: This works for text-based files (HTML, JSON, TXT, etc.). If you're working with binary files, you'd use different methods (like
response.blob()), but since you're inserting content into an HTML div, text is probably what you need.
内容的提问来源于stack exchange,提问作者Erik Klatscho

