0

I need to get HTML page, enqueue CSS and JS files to it "on the fly" and then display it in the browser with NodeJS app file. I mean without changing HTML code of the page before getting it by NodeJS. Both CSS and JS files are in the same folder as NodeJS app file.

I'm trying this way

var fs = require('fs');
var http = require('http');
http.createServer(function (req, res) {
if(req.url === '/favicon.ico') {
    res.writeHead(404);
    res.end();
    return;
}

var indexPageHTML = fs.readFileSync('index.html');
var indexPageHTML = indexPageHTML.toString();
var indexPageHTML = indexPageHTML.split('</head>')[0]+'<link rel="stylesheet" type="text/css" href="style.css"></head>'+indexPageHTML.split('</head>')[1];
var indexPageHTML = indexPageHTML.split('</body>')[0]+'<script src="my_client_script.js"></script></body></html>';

res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
res.end(indexPageHTML);
}).listen(80, 'localhost');

my minified index.html

<!doctype html><html><head><meta charset="utf-8"><title>Homepage title</title>
<style>html,body{height:100%;}</style></head><body>
<header></header>
<main role="main"></main>
<footer></footer>
</body></html>

In the browser I get the code I need, but none of files are loaded (CSS are not applied and JS doesn't work on the page) and in the browser console I get the error

Uncaught SyntaxError: Unexpected token <

and the warning

Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost/app_style.css".

How to resolve the problem?

ps. I'm working with NodeJS in local computer on disk C inside of C:/User/Username

1
  • 1
    You are serving the same HTML in response to every request. Even the request for the styles.css was receiving the HTML content. Commented Oct 29, 2018 at 23:26

1 Answer 1

0

Ok, I've found the answer by the link NodeJS can't load css file

Just added the code

...
if(mimeType == 'text/html') {
    var contents = contents.toString();
    var contents = contents.split('</head>')[0]+'<link rel="stylesheet" type="text/css" href="style.css"></head>'+contents.split('</head>')[1];
    var contents = contents.split('</body>')[0]+'<script src="my_client_script.js"></script></body></html>';
}
res.end(contents);
...

to the getFile() function

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.