Trying to highlight an external file main.cpp with highlight.js I put together the following:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css">
<title>My Node.js Server</title>
</head>
<body>
<h1>Hello from Node.js!</h1>
<pre><code class="cpp" id="codeContainer">int x = 5;</code></pre>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<!-- and it's easy to individually load additional languages -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/cpp.min.js"></script> -->
<script>hljs.initHighlightingOnLoad();</script>
<script>
document.write("casdca");
</script>
<script>
fetch('main.cpp')
.then(response => response.text())
.then(text => {
const codeContainer = document.getElementById('codeContainer');
codeContainer.textContent = text;
hljs.highlightElement(codeContainer);
});
hljs.initHighlightingOnLoad();
</script>
</body>
</html>
However it seems page loading is failing, since I see the actual index.html source code in the browser.
Comment on codeContainer.textContent = text; and following lines depending on it cause the page to load, but not presenting main.cpp obviously.
All this is being loaded by
node node.js
which is
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
fs.readFile(path.join(__dirname, 'index.html'), (err, data) => {
if (err) {
res.writeHead(500);
res.end("Error loading the page");
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Wondering what I'm missing. Appreciate if one can give me some directions.
node.js
Using highlightjs
index.html
Using prism.js
index.html
prism is better because it shows line numbers, the copy button, match-braces, and other plugins.