user3491963
user3491963

Reputation: 33

execute javascript from html - node.js

I hava an html file that execute js file inside. Now I want to run this with Node.js server. I can see that it write the html file in it (it write 'hi (:') but ignored the js file.

this is the 'server.js' file:

var fs = require('fs');
var http = require('http');
var content;
//read the file
fs.readFile('index.html', function read(err, html) {
    if (err)
    {
        throw err;
    }

    content = html;

http.createServer(function(request,response)
{
    response.writeHead(200,{"Content-Type": "text/html"});
    response.write(html);
    response.end();
}).listen(8081);

console.log("listening on port 8081");
});

and this is the 'index.html' file:

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
        <script src="script.js"> </script>
        <script> </script>
        </head>
    <body>
        <div id="empty">
            hi :)
        </div>
    </body>
</html>

Thanks for your help! (:

Upvotes: 0

Views: 2044

Answers (1)

Michelle Tilley
Michelle Tilley

Reputation: 159095

You've created a server that responds to every single request with the contents of index.html--so when the <script> tag asks the server for the script.js file, the server incorrectly sends it index.html again.

In your createServer handler, you'll want to look at the incoming request and figure out which file the request is asking for, and send different data back accordingly.

To handle this situation more robustly, where you don't have to have an if statement for every file you might want to send, you can use an abstraction over your createServer handler to detect and send static files automatically. This question contains several solutions that may help put you on the right track.

Upvotes: 1

Related Questions