Closed Stunext closed 2 years ago
app.get('/',res=>res.end(view({text:'123'})))
const view=data=>`<html><body>${data.text}</body></html>`
add header text/html
res.writeHeader('content-type', 'text/html')
res.end('my html code')
What about a entire HTML file?
If you are trying to generate a string you can use any template library or I recommend Vanilla JS no library needed, using external file you would do:
// view.js file
module.exports=data=>`
<html>
<body>
${data.text}
</body>
</html>
`
// server
const view=require('./view.js')
const htmlString=view(data)
Tell your text editor to use HTML syntax for view.js file so it will highlight as HTML
if you need to output static, you need to look at examples with streaming video
if you try to respond with the contents of a html or any other file this is how i did it:
const mime = require('mime');
const fileName = 'path/to/file.html';
try {
const readStream = toArrayBuffer(fs.readFileSync(fileName));
res.cork(() => {
res.writeHeader('Content-Type', mime.getType(fileName););
res.end(readStream);
});
} catch (err) {
res.cork(() => {
res.writeStatus('404').end('Not here');
});
and this is the function
toArrayBuffer(buffer) {
return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
}
You can also consider adding some security Headers, safe resolve the file path, noCache or Cache and also Content-Encoding gzip, deflate or no encoding
you can take a ready-made server and not suffer
@sanchezzzhak Are you suffering? This is easy stuff, don't confuse him by pasting bunch of unnecessary code, and different library no one should be using
@Wyzix33 You are both assuming static files, he asked for HTML View, usually that means a Template that gets updated with different data on every render, but who knows what he is talking about
@Stunext Are you asking how to open a basic HTML file? You should probably read https://nodejs.org/api/fs.html
How to return a simple html view?