I'm trying to load an HTML file in JavaScript and displaying it into an html container with this JavaScript code
fs = require('fs')
fs.readFile('index-dashboard.html', (err, data) => {
document.getElementById('index-right-container').innerHTML = data
})
and I've already create the container and given it an ID of "index-right-container" as I've used above. but the HTML won't load and display in the container can anyone help me out?
thanks.
CodePudding user response:
You are trying to use the fs
package which is used in node.js. It doesn't work in the browser. You can try doing this with fetch
:
function loadHTML(){
fetch('index-dashboard.html')
.then(response=> response.text())
.then(text=> document.getElementById('index-right-container').innerHTML = text);
}
CodePudding user response:
FS is the Node.js File System Module. It is meant to be run server-side using Node, which is a runtime for JavaScript. You won't be able to use it to read files client-side like you are trying to do here.
Interacting with local files using JavaScript can be difficult due to security restrictions on browsers. If the user selects the file themselves via a file input, you can read it using File API's FileReader:
function readFile(input) {
let file = input.files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
console.log(reader.result);
};
reader.onerror = function() {
console.log(reader.error);
};
}
<input type="file" onchange="readFile(this)">
If this solution isn't workable for your case, you will need to host the file on a server and retrieve its contents from there. Modern browsers will not allow you to access the user's local file system using the file:// protocol as it is a security concern.
CodePudding user response:
You could do something like:
document.getElementById("index-right-container").innerHTML='<object type="text/html" data="index-dashboard.html" ></object>';