0

I'm having trouble loading my jquery file or any file for that matter in a node.js read html file. I spent quite some time on this and noticed that the web based google hosted library file works fine, but my local file does not. I cannot figure out why, perhaps I'm not directing it to the correct directory, but I'm not sure where else I would put it or direct it.

Directory includes these 3 files

index.html
jquery.min.js
loadfile.js

index.html The commented out google hosted jquery file works just fine. But the local does not.

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript" src="jquery.min.js"></script>
        <!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>  -->
        <script type="text/javascript">
            $(document).ready(function() {
                alert("test");
            });
        </script>
    </head>
    <body>
        Hi!
    </body>
</html>

Here is the file I load with node. loadfile.js

var http = require('http');
var url = require('url');
var fs = require('fs');


server = http.createServer(function (request, response) {
    current_url = url.parse(request.url).pathname;

    file_path = __dirname + current_url;    

    var tmp = file_path.lastIndexOf('.');
    var ext = file_path.substring(tmp + 1);

    console.log(ext);

    if(ext == 'js')
        response.writeHead(200, {'Content-type': 'text/javascript'});
    else if(ext == 'css')
        response.writeHead(200, {'Content-type': 'text/css'});
    else
        response.writeHead(200, {'Content-type': 'text/html'});

    if(current_url == '/') {
        fs.readFile('index.html', 'utf8', function (errors, contents) {
            response.end(contents); 
        });
    } else {
        response.end();
    }

});

server.listen(8000);
console.log("Running in localhost at port 8000");

I get this error Uncaught ReferenceError: $ is not defined on the $(document).ready line since it doesn't seem to think I loaded the jquery.

Any help would be appreciated. I could always use the google hosted file, but this doesn't sit well with me. Thanks in advance!

1 Answer 1

3

You haven't actually serve the file if the current_url isn't "/", right now your server can only send the file content of index.html to the client.

You need to have something like the following in your "else" clause:

fs.readFile(file_path, 'utf8', function (errors, contents) {
    response.end(contents); 
});
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.